The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/refactor triggers to remove mobx (#35254)
Joshen Limdd03625f557d
diff --git a/apps/studio/components/interfaces/Database/Triggers/ChooseFunctionForm.tsx b/apps/studio/components/interfaces/Database/Triggers/ChooseFunctionForm.tsxindex 1fcae2033dc..809bb86edd0 100644--- a/apps/studio/components/interfaces/Database/Triggers/ChooseFunctionForm.tsx+++ b/apps/studio/components/interfaces/Database/Triggers/ChooseFunctionForm.tsx@@ -9,27 +9,33 @@ import { Button, SidePanel } from 'ui'import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'import InformationBox from 'components/ui/InformationBox'import SqlEditor from 'components/ui/SqlEditor'-import type { DatabaseFunction } from 'data/database-functions/database-functions-query'-import { HelpCircle, Terminal, ChevronDown } from 'lucide-react'+import {+ useDatabaseFunctionsQuery,+ type DatabaseFunction,+} from 'data/database-functions/database-functions-query'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import { ChevronDown, HelpCircle, Terminal } from 'lucide-react'export interface ChooseFunctionFormProps {- triggerFunctions: DatabaseFunction[]visible: boolean- onChange: (id: number) => voidsetVisible: (value: boolean) => void+ onChange: (fn: DatabaseFunction) => void}-const ChooseFunctionForm = ({- triggerFunctions,- visible,- onChange,- setVisible,-}: ChooseFunctionFormProps) => {+const ChooseFunctionForm = ({ visible, onChange, setVisible }: ChooseFunctionFormProps) => {+ const project = useSelectedProject()++ const { data = [] } = useDatabaseFunctionsQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })+ const triggerFunctions = data.filter((fn) => fn.return_type === 'trigger')const hasPublicSchemaFunctions = triggerFunctions.length >= 1const functionSchemas = lodashMap(uniqBy(triggerFunctions, 'schema'), 'schema')- function selectFunction(id: number) {- onChange(id)+ const selectFunction = (id: number) => {+ const fn = triggerFunctions.find((x) => x.id === id)+ if (!!fn) onChange(fn)setVisible(!visible)}diff --git a/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx b/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsxdeleted file mode 100644index 8cf605d89f1..00000000000--- a/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx+++ /dev/null@@ -1,792 +0,0 @@-import { has, isEmpty, mapValues, union, without } from 'lodash'-import { makeAutoObservable } from 'mobx'-import { observer, useLocalObservable } from 'mobx-react-lite'-import { createContext, useContext, useEffect, useState } from 'react'-import SVG from 'react-inlinesvg'-import { toast } from 'sonner'-import { Badge, Button, Checkbox, Input, Listbox, SidePanel } from 'ui'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'--import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'-import CodeEditor from 'components/ui/CodeEditor/CodeEditor'-import FormEmptyBox from 'components/ui/FormBoxEmpty'-import NoTableState from 'components/ui/States/NoTableState'-import {- DatabaseFunction,- useDatabaseFunctionsQuery,-} from 'data/database-functions/database-functions-query'-import { useDatabaseTriggerCreateMutation } from 'data/database-triggers/database-trigger-create-mutation'-import { useDatabaseTriggerUpdateMutation } from 'data/database-triggers/database-trigger-update-mutation'-import { useTablesQuery } from 'data/tables/tables-query'-import { BASE_PATH } from 'lib/constants'-import { PROTECTED_SCHEMAS } from 'lib/constants/schemas'-import { PauseCircle, PlayCircle, Terminal } from 'lucide-react'-import type { Dictionary } from 'types'-import ChooseFunctionForm from './ChooseFunctionForm'--class CreateTriggerFormState {- id: number | undefined- originalName: string | undefined- // @ts-ignore- activation: { value: string; error?: string }- // @ts-ignore- enabledMode: { value: string }- // @ts-ignore- events: { value: string[]; error?: string }- // @ts-ignore- functionName: { value: string; error?: string }- // @ts-ignore- functionSchema: { value: string; error?: string }- // @ts-ignore- orientation: { value: string; error?: string }- // @ts-ignore- name: { value: string; error?: string }- // @ts-ignore- schema: { value: string }- // @ts-ignore- table: { value: string }- // @ts-ignore- tableId: { value: number; error?: string }- // @ts-ignore- condition: { value: string }-- constructor() {- makeAutoObservable(this)- this.reset()- }-- get requestBody() {- return {- id: this.id,- activation: this.activation.value,- enabled_mode: this.enabledMode.value,- events: this.events.value,- function_name: this.functionName.value,- function_schema: this.functionSchema.value,- orientation: this.orientation.value,- name: this.name.value,- schema: this.schema.value,- table: this.table.value,- }- }-- reset(trigger?: Dictionary<any>) {- this.id = trigger?.id- this.originalName = trigger?.name- this.activation = { value: trigger?.activation ?? 'BEFORE' }- this.enabledMode = { value: trigger?.enabled_mode ?? 'ORIGIN' }- this.events = { value: trigger?.events ?? [] }- this.functionName = { value: trigger?.function_name ?? '' }- this.functionSchema = { value: trigger?.function_schema ?? '' }- this.orientation = { value: trigger?.orientation ?? 'STATEMENT' }- this.name = { value: trigger?.name ?? '' }- this.schema = { value: trigger?.schema ?? '' }- this.table = { value: trigger?.table ?? '' }- this.tableId = { value: trigger?.table_id ?? '' }- this.condition = { value: trigger?.condition ?? '' }- }-- update(state: Dictionary<any>) {- this.activation = state.activation- this.enabledMode = state.enabledMode- this.events = state.events- this.functionName = state.functionName- this.functionSchema = state.functionSchema- this.orientation = state.orientation- this.name = state.name- this.schema = state.schema- this.table = state.table- this.tableId = state.tableId- }-}--interface ICreateTriggerStore {- chooseFunctionFormVisible: boolean- formState: CreateTriggerFormState- meta: any- tables: Dictionary<any>[]- onFormChange: ({ key, value }: { key: string; value: any }) => void- onSelectFunction: (fn: DatabaseFunction) => void- setChooseFunctionFormVisible: (value: boolean) => void- setDefaultSelectedTable: () => void- setTables: (value: any[]) => void- validateForm: () => boolean-}--class CreateTriggerStore implements ICreateTriggerStore {- chooseFunctionFormVisible = false- formState = new CreateTriggerFormState()- meta = null- tables = []- isDirty = false-- constructor() {- makeAutoObservable(this)- }-- get isEditing() {- return this.formState.id != undefined- }-- setChooseFunctionFormVisible = (value: boolean) => {- this.chooseFunctionFormVisible = value- }-- // set first table as default selection- setDefaultSelectedTable = () => {- if (this.tables?.length != 0) {- this.formState.table.value = (this.tables[0] as any).name- this.formState.schema.value = (this.tables[0] as any).schema- this.formState.tableId.value = (this.tables[0] as any).id- }- }-- setisDirty = (value: boolean) => {- this.isDirty = value- }-- setTables = (value: any[]) => {- this.tables = value- .sort((a, b) => a.schema.localeCompare(b.schema))- .filter((a) => !PROTECTED_SCHEMAS.includes(a.schema)) as any- this.setDefaultSelectedTable()- }-- onFormChange = ({ key, value }: { key: string; value: any }) => {- this.isDirty = true- if (has(this.formState, key)) {- const temp = (this.formState as any)[key]- // @ts-ignore- this.formState[key] = { ...temp, value, error: undefined }- } else {- // @ts-ignore- this.formState[key] = { value }- }- }-- onSelectFunction = (fn: DatabaseFunction) => {- this.formState.functionName.value = fn.name- this.formState.functionSchema.value = fn.schema- }-- validateForm = () => {- let isValidated = true- const _state = mapValues(this.formState, (x: { value: any }, key: string) => {- switch (key) {- case 'name': {- if (isEmpty(x.value) || hasWhitespace(x.value)) {- isValidated = false- return { ...x, error: 'Invalid trigger name' }- } else {- return x- }- }- case 'activation': {- if (isEmpty(x.value)) {- isValidated = false- return { ...x, error: 'you have an error' }- } else {- return x- }- }- case 'events': {- if (isEmpty(x.value)) {- isValidated = false- return { ...x, error: 'Select at least 1 event' }- } else {- return x- }- }- case 'tableId': {- if (isEmpty(`${x.value}`)) {- isValidated = false- return { ...x, error: 'You must choose a table' }- } else {- return x- }- }- default:- return x- }- })- if (!isValidated) {- this.formState.update(_state)- }- return isValidated- }-}--function hasWhitespace(value: string) {- return /\s/.test(value)-}--const CreateTriggerContext = createContext<ICreateTriggerStore | null>(null)--interface CreateTriggerProps {- trigger?: any- visible: boolean- setVisible: (value: boolean) => void-}--const CreateTrigger = ({ trigger, visible, setVisible }: CreateTriggerProps) => {- const { project } = useProjectContext()- const [isClosingPanel, setIsClosingPanel] = useState(false)- const _localState = useLocalObservable(() => new CreateTriggerStore())-- useTablesQuery(- {- projectRef: project?.ref,- connectionString: project?.connectionString,- },- {- onSuccess(tables) {- if (_localState.tables.length <= 0) {- _localState.setTables(tables)- }- },- }- )-- const { data } = useDatabaseFunctionsQuery({- projectRef: project?.ref,- connectionString: project?.connectionString,- })- const triggerFunctions = (data ?? []).filter((fn) => fn.return_type === 'trigger')-- const { mutate: createDatabaseTrigger, isLoading: isCreating } =- useDatabaseTriggerCreateMutation()- const { mutate: updateDatabaseTrigger, isLoading: isUpdating } =- useDatabaseTriggerUpdateMutation()-- useEffect(() => {- _localState.setisDirty(false)- if (trigger) {- _localState.formState.reset(trigger)- } else {- _localState.formState.reset()- _localState.setDefaultSelectedTable()- }- }, [visible, trigger])-- async function handleSubmit() {- if (!project) return console.error('Project is required')-- if (_localState.validateForm()) {- const body = _localState.formState.requestBody- if (_localState.isEditing && body.id) {- updateDatabaseTrigger(- {- projectRef: project?.ref,- connectionString: project?.connectionString,- id: body.id,- payload: body,- },- {- onSuccess: () => {- toast.success(`Successfully updated trigger ${body.name}`)- setVisible(!visible)- },- onError: (error) => {- toast.error(`Failed to update trigger: ${error.message}`)- },- }- )- } else {- createDatabaseTrigger(- {- projectRef: project?.ref,- connectionString: project?.connectionString,- payload: body,- },- {- onSuccess: () => {- toast.success(`Successfully created trigger ${body.name}`)- setVisible(!visible)- },- onError: (error) => {- toast.error(`Failed to create trigger: ${error.message}`)- },- }- )- }- }- }-- const hasPublicTables = _localState.tables.length >= 1-- const isClosingSidePanel = () => {- _localState.isDirty ? setIsClosingPanel(true) : setVisible(!visible)- }-- return (- <>- <SidePanel- size="large"- visible={visible}- onCancel={isClosingSidePanel}- header={- _localState.formState.id- ? `Edit '${_localState.formState.originalName}' trigger`- : 'Add a new Trigger'- }- hideFooter={!hasPublicTables}- className={- _localState.chooseFunctionFormVisible- ? 'hooks-sidepanel mr-16 transform transition-all duration-300 ease-in-out'- : 'hooks-sidepanel mr-0 transform transition-all duration-300 ease-in-out'- }- loading={isCreating || isUpdating}- onConfirm={handleSubmit}- >- {hasPublicTables ? (- <div>- <CreateTriggerContext.Provider value={_localState}>- <div className="my-6 space-y-10">- {_localState.isEditing ? (- <div className="space-y-6 px-6">- <InputName />- <SelectEnabledMode />- {_localState.formState.condition.value && <DisplayCondition />}- </div>- ) : (- <>- <div className="px-6">- <InputName />- </div>- <SidePanel.Separator />- <div className="space-y-12 px-6">- <h5>Conditions to fire trigger</h5>- <ListboxTable />- <CheckboxEvents />- <ListboxActivation />- <SelectOrientation />- </div>- <SidePanel.Separator />- <FunctionForm />- </>- )}- </div>- <ChooseFunctionForm- triggerFunctions={triggerFunctions}- visible={_localState.chooseFunctionFormVisible}- setVisible={_localState.setChooseFunctionFormVisible}- onChange={(id: number) => {- const selectedFn = (data ?? []).find((fn) => fn.id === id)- if (selectedFn) _localState.onSelectFunction(selectedFn)- }}- />- </CreateTriggerContext.Provider>- <ConfirmationModal- visible={isClosingPanel}- title="Discard changes"- confirmLabel="Discard"- onCancel={() => setIsClosingPanel(false)}- onConfirm={() => {- setIsClosingPanel(false)- setVisible(!visible)- }}- >- <p className="text-sm text-foreground-light">- There are unsaved changes. Are you sure you want to close the panel? Your changes- will be lost.- </p>- </ConfirmationModal>- </div>- ) : (- <NoTableState message="You will need to create a table first before you can make a trigger" />- )}- </SidePanel>- </>- )-}--export default observer(CreateTrigger)--const InputName = observer(({}) => {- const _localState = useContext(CreateTriggerContext)- return (- <Input- id="name"- label="Name of trigger"- layout="horizontal"- placeholder="Name of trigger"- value={_localState!.formState.name.value}- onChange={(e) =>- _localState!.onFormChange({- key: 'name',- value: e.target.value,- })- }- size="small"- error={_localState!.formState.name.error}- descriptionText="The name is also stored as the actual postgres name of the trigger. Do not use spaces/whitespace."- />- )-})--const SelectEnabledMode = observer(({}) => {- const _localState = useContext(CreateTriggerContext)- return (- <Listbox- id="enabled-mode"- label="Enabled mode"- layout="horizontal"- value={_localState!.formState.enabledMode.value}- onChange={(value) =>- _localState!.onFormChange({- key: 'enabledMode',- value: value,- })- }- size="small"- descriptionText="Determines if a trigger should or should not fire. Can also be used to disable a trigger, but not delete it."- >- <Listbox.Option- addOnBefore={({ active, selected }: any) => {- return (- <div className="h-3 w-3 rounded-full border border-green-700 bg-green-900 shadow-sm"></div>- )- }}- value="ORIGIN"- label="Origin"- >- Origin- <span className="block text-foreground-lighter">This is a default behavior</span>- </Listbox.Option>- <Listbox.Option- addOnBefore={({ active, selected }: any) => {- return (- <div className="h-3 w-3 rounded-full border border-green-700 bg-green-900 shadow-sm"></div>- )- }}- value="REPLICA"- label="Replica"- >- Replica- <span className="block text-foreground-lighter">- Will only fire if the session is in “replica” mode- </span>- </Listbox.Option>- <Listbox.Option- addOnBefore={({ active, selected }: any) => {- return (- <div className="h-3 w-3 rounded-full border border-green-700 bg-green-900 shadow-sm"></div>- )- }}- value="ALWAYS"- label="Always"- >- Always- <span className="block text-foreground-lighter">- Will fire regardless of the current replication role- </span>- </Listbox.Option>- <Listbox.Option- addOnBefore={({ active, selected }: any) => {- return (- <div className="h-3 w-3 rounded-full border border-red-700 bg-red-900 shadow-sm"></div>- )- }}- value="DISABLED"- label="Disabled"- >- Disabled- <span className="block text-foreground-lighter">Will not fire</span>- </Listbox.Option>- </Listbox>- )-})--const DisplayCondition = observer(() => {- const _localState = useContext(CreateTriggerContext)-- return (- <div className="text-sm leading-4 grid gap-2 md:grid md:grid-cols-12">- <div className="flex flex-col space-y-2 col-span-4">- <label className="block text-foreground-light text-sm leading-4 break-all">Condition</label>- </div>- <div className="col-span-8 h-[100px]">- <CodeEditor- isReadOnly- autofocus={false}- id={`trigger-condition-${_localState!.formState.id}`}- language="pgsql"- defaultValue={_localState!.formState.condition.value}- />- <div className="mt-2 text-foreground-lighter leading-normal text-sm">- This condition must be met for the trigger to fire.- <br />- <span className="text-foreground">- To update the condition, you must drop and recreate this trigger.- </span>- </div>- </div>- </div>- )-})--const SelectOrientation = observer(({}) => {- const _localState = useContext(CreateTriggerContext)- return (- <Listbox- id="orientation"- label="Orientation"- layout="horizontal"- value={_localState!.formState.orientation.value}- onChange={(value) =>- _localState!.onFormChange({- key: 'orientation',- value: value,- })- }- size="small"- descriptionText="Identifies whether the trigger fires once for each processed row or once for each statement"- >- <Listbox.Option value="ROW" label="Row">- Row- <span className="block text-foreground-lighter">fires once for each processed row</span>- </Listbox.Option>- <Listbox.Option value="STATEMENT" label="Statement">- Statement- <span className="block text-foreground-lighter">fires once for each statement</span>- </Listbox.Option>- </Listbox>- )-})--const ListboxTable = observer(({}) => {- const _localState = useContext(CreateTriggerContext)-- return (- <Listbox- id="table"- label="Table"- layout="horizontal"- value={_localState!.formState.tableId.value}- onChange={(id) => {- const _table = _localState!.tables.find((x) => x.id === id)- if (_table) {- _localState!.onFormChange({- key: 'table',- value: _table.name,- })- _localState!.onFormChange({- key: 'schema',- value: _table.schema,- })- _localState!.onFormChange({- key: 'tableId',- value: id,- })- }- }}- size="small"- error={_localState!.formState.tableId.error}- descriptionText="This is the table the trigger will watch for changes. You can only select 1 table for a trigger."- >- {_localState!.tables.map((x) => {- return (- <Listbox.Option- id={x.id}- key={x.id}- value={x.id}- label={x.name}- addOnBefore={() => (- <div className="flex items-center justify-center rounded bg-foreground p-1 text-background">- <SVG- src={`${BASE_PATH}/img/table-editor.svg`}- style={{ width: `16px`, height: `16px`, strokeWidth: '1px' }}- preProcessor={(code) =>- code.replace(/svg/, 'svg class="m-auto text-color-inherit"')- }- />- </div>- )}- >- <div className="flex flex-row items-center space-x-1">- <p className="text-sm text-foreground-light">{x.schema}</p>- <p className="text-foreground">{x.name}</p>- </div>- </Listbox.Option>- )- })}- </Listbox>- )-})--const CheckboxEvents = observer(({}) => {- const _localState = useContext(CreateTriggerContext)- return (- // @ts-ignore- <Checkbox.Group- name="events"- label="Events"- id="events"- labelOptional="The type of events that will trigger your trigger"- layout="horizontal"- descriptionText="These are the events that are watched by the trigger, only the events selected above will fire the trigger on the table you've selected."- size="small"- onChange={(e) => {- const temp = _localState!.formState.events.value- const value = e.target.checked- ? union(temp, [e.target.value])- : without(temp, e.target.value)- _localState!.onFormChange({- key: 'events',- value: value,- })- }}- error={_localState!.formState.events.error}- >- <Checkbox- value="INSERT"- label="Insert"- description={'Any insert operation on the table'}- checked={_localState!.formState.events.value.includes('INSERT')}- />- <Checkbox- value="UPDATE"- label="Update"- description="Any update operation, of any column in the table"- checked={_localState!.formState.events.value.includes('UPDATE')}- />- <Checkbox- value="DELETE"- label="Delete"- description="Any deletion of a record"- checked={_localState!.formState.events.value.includes('DELETE')}- />- </Checkbox.Group>- )-})--const ListboxActivation = observer(({}) => {- const _localState = useContext(CreateTriggerContext)- return (- <Listbox- id="activation"- label="Trigger type"- descriptionText="This determines when your Hook fires"- onChange={(_value) => {- _localState!.onFormChange({- key: 'activation',- value: _value,- })- }}- value={_localState!.formState.activation.value}- layout="horizontal"- size="small"- error={_localState!.formState.activation.error}- >- <Listbox.Option- id={'before'}- value={'BEFORE'}- label={'Before the event'}- addOnBefore={() => (- <div className="flex items-center justify-center rounded bg-foreground p-1 text-background">- <PauseCircle strokeWidth={2} size="18" />- </div>- )}- >- <div className="flex flex-col">- <span>{'before'}</span>- <span className="block text-foreground-lighter">- Trigger fires before the operation is attempted- </span>- </div>- </Listbox.Option>- <Listbox.Option- id={'after'}- value={'AFTER'}- label={'After the event'}- addOnBefore={() => (- <div className="flex items-center justify-center rounded bg-green-1200 p-1 text-background">- <PlayCircle strokeWidth={2} size="18" />- </div>- )}- >- <div className="flex flex-col">- <span>{'after'}</span>- <span className="block text-foreground-lighter">- Trigger fires after the operation has completed- </span>- </div>- </Listbox.Option>- </Listbox>- )-})--const FunctionForm = observer(({}) => {- const _localState = useContext(CreateTriggerContext)-- return (- <div className="space-y-4">- <div className="space-y-6 px-6">- <h5>Function to trigger</h5>- </div>- <div className="px-6">- {isEmpty(_localState!.formState.functionName.value) ? (- <FunctionEmpty />- ) : (- <FunctionWithArguments />- )}- </div>- </div>- )-})--const FunctionEmpty = observer(({}) => {- const _localState = useContext(CreateTriggerContext)- return (- <button- type="button"- onClick={() => _localState!.setChooseFunctionFormVisible(true)}- className={[- 'relative w-full',- 'rounded',- 'border border-default',- 'bg-surface-200 px-5 py-1',- 'shadow-sm transition-all',- 'hover:border-strong hover:bg-overlay-hover',- ].join(' ')}- >- <FormEmptyBox- icon={<Terminal size={14} strokeWidth={2} />}- text="Choose a function to trigger"- />- </button>- )-})--const FunctionWithArguments = observer(({}) => {- const _localState = useContext(CreateTriggerContext)-- return (- <>- <div- className={[- 'relative w-full',- 'flex items-center justify-between',- 'space-x-3 px-5 py-4',- 'border border-default',- 'rounded shadow-sm transition-shadow',- ].join(' ')}- >- <div className="flex items-center gap-2">- <div className="flex h-6 w-6 items-center justify-center rounded bg-foreground text-background focus-within:bg-opacity-10">- <Terminal size="18" strokeWidth={2} width={14} />- </div>- <div className="flex items-center gap-2">- <p className="text-foreground-light">{_localState!.formState.functionName.value}</p>- <div>- <Badge>{_localState!.formState.functionSchema.value}</Badge>- </div>- </div>- </div>- <Button type="default" onClick={() => _localState!.setChooseFunctionFormVisible(true)}>- Change function- </Button>- </div>- </>- )-})diff --git a/apps/studio/components/interfaces/Database/Triggers/DeleteTrigger.tsx b/apps/studio/components/interfaces/Database/Triggers/DeleteTrigger.tsxindex f2131e29369..d57da933a45 100644--- a/apps/studio/components/interfaces/Database/Triggers/DeleteTrigger.tsx+++ b/apps/studio/components/interfaces/Database/Triggers/DeleteTrigger.tsx@@ -1,3 +1,4 @@+import { PostgresTrigger } from '@supabase/postgres-meta'import { toast } from 'sonner'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'@@ -5,12 +6,12 @@ import { useDatabaseTriggerDeleteMutation } from 'data/database-triggers/databasimport TextConfirmModal from 'ui-patterns/Dialogs/TextConfirmModal'interface DeleteTriggerProps {- trigger?: any+ trigger?: PostgresTriggervisible: booleansetVisible: (value: boolean) => void}-const DeleteTrigger = ({ trigger, visible, setVisible }: DeleteTriggerProps) => {+export const DeleteTrigger = ({ trigger, visible, setVisible }: DeleteTriggerProps) => {const { project } = useProjectContext()const { id, name, schema } = trigger ?? {}@@ -45,7 +46,7 @@ const DeleteTrigger = ({ trigger, visible, setVisible }: DeleteTriggerProps) =>loading={isLoading}confirmLabel={`Delete trigger ${name}`}confirmPlaceholder="Type in name of trigger"- confirmString={name}+ confirmString={name ?? ''}text={<>This will delete your trigger called{' '}@@ -59,5 +60,3 @@ const DeleteTrigger = ({ trigger, visible, setVisible }: DeleteTriggerProps) =>/>)}--export default DeleteTriggerdiff --git a/apps/studio/components/interfaces/Database/Triggers/TriggerSheet.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggerSheet.tsxnew file mode 100644index 00000000000..78b68d7f8ed--- /dev/null+++ b/apps/studio/components/interfaces/Database/Triggers/TriggerSheet.tsx@@ -0,0 +1,448 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { Terminal } from 'lucide-react'+import { useEffect, useState } from 'react'+import { SubmitHandler, useForm } from 'react-hook-form'+import { toast } from 'sonner'+import * as z from 'zod'++import { PostgresTrigger } from '@supabase/postgres-meta'+import FormBoxEmpty from 'components/ui/FormBoxEmpty'+import { useDatabaseTriggerCreateMutation } from 'data/database-triggers/database-trigger-create-mutation'+import { useDatabaseTriggerUpdateMutation } from 'data/database-triggers/database-trigger-update-mutation'+import { useTablesQuery } from 'data/tables/tables-query'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import { PROTECTED_SCHEMAS } from 'lib/constants/schemas'+import {+ Button,+ Checkbox_Shadcn_,+ cn,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Input_Shadcn_,+ Select_Shadcn_,+ SelectContent_Shadcn_,+ SelectItem_Shadcn_,+ SelectTrigger_Shadcn_,+ SelectValue_Shadcn_,+ Separator,+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import ChooseFunctionForm from './ChooseFunctionForm'+import {+ TRIGGER_ENABLED_MODES,+ TRIGGER_EVENTS,+ TRIGGER_ORIENTATIONS,+ TRIGGER_TYPES,+} from './Triggers.constants'++const formId = 'create-trigger'++const FormSchema = z.object({+ name: z+ .string()+ .min(1, 'Please provide a name for your trigger')+ .regex(/^\S+$/, 'Name should not contain spaces or whitespaces'),+ schema: z.string(),+ table: z.string(),+ activation: z.string(),+ enabled_mode: z.string(),+ orientation: z.string(),+ function_name: z.string(),+ function_schema: z.string(),+ events: z.array(z.string()).min(1, 'Please select at least one event'),++ // For UI handling, not to be passed to the final request+ tableId: z.string().optional(),+})++const defaultValues = {+ name: '',+ schema: '',+ table: '',+ activation: 'AFTER',+ orientation: 'ROW',+ function_name: '',+ function_schema: '',+ enabled_mode: 'ORIGIN',+ events: [],+}++interface TriggerSheetProps {+ selectedTrigger?: PostgresTrigger+ open: boolean+ setOpen: (val: boolean) => void+}++export const TriggerSheet = ({ selectedTrigger, open, setOpen }: TriggerSheetProps) => {+ const project = useSelectedProject()++ const [showFunctionSelector, setShowFunctionSelector] = useState(false)++ const { mutate: createDatabaseTrigger, isLoading: isCreating } = useDatabaseTriggerCreateMutation(+ {+ onSuccess: (res) => {+ toast.success(`Successfully created trigger ${res.name}`)+ setOpen(false)+ },+ onError: (error) => {+ toast.error(`Failed to create trigger: ${error.message}`)+ },+ }+ )+ const { mutate: updateDatabaseTrigger, isLoading: isUpdating } = useDatabaseTriggerUpdateMutation(+ {+ onSuccess: (res) => {+ toast.success(`Successfully updated trigger ${res.name}`)+ setOpen(false)+ },+ onError: (error) => {+ toast.error(`Failed to update trigger: ${error.message}`)+ },+ }+ )++ const { data = [], isSuccess } = useTablesQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })++ const tables = data+ .sort((a, b) => a.schema.localeCompare(b.schema))+ .filter((a) => !PROTECTED_SCHEMAS.includes(a.schema))+ const isEditing = !!selectedTrigger++ const form = useForm<z.infer<typeof FormSchema>>({+ mode: 'onSubmit',+ reValidateMode: 'onSubmit',+ resolver: zodResolver(FormSchema),+ defaultValues,+ })+ const { function_name, function_schema } = form.watch()++ const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (values) => {+ if (!project) return console.error('Project is required')+ const { tableId, ...payload } = values++ if (isEditing) {+ updateDatabaseTrigger({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ id: selectedTrigger.id,+ payload: { name: payload.name, enabled_mode: payload.enabled_mode },+ })+ } else {+ createDatabaseTrigger({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ payload,+ })+ }+ }++ useEffect(() => {+ if (open && isSuccess) {+ form.clearErrors()++ if (isEditing) {+ form.reset(selectedTrigger)+ } else {+ form.reset({+ ...defaultValues,+ tableId: tables[0].id.toString(),+ table: tables[0].name,+ schema: tables[0].schema,+ })+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, isSuccess])++ return (+ <>+ <Sheet open={open} onOpenChange={setOpen}>+ <SheetContent size="lg" className="flex flex-col gap-0">+ <SheetHeader>+ <SheetTitle>Create a new database trigger</SheetTitle>+ </SheetHeader>++ <Form_Shadcn_ {...form}>+ <form+ id={formId}+ className="flex-1 flex flex-col gap-y-6 overflow-auto py-6"+ onSubmit={form.handleSubmit(onSubmit)}+ >+ <FormField_Shadcn_+ name="name"+ control={form.control}+ render={({ field }) => (+ <FormItemLayout+ className="px-5"+ layout="horizontal"+ label="Name of trigger"+ description="Do not use spaces/whitespace."+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_ {...field} placeholder="Name of trigger" />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ {isEditing ? (+ <FormField_Shadcn_+ name="enabled_mode"+ control={form.control}+ render={({ field }) => (+ <FormItemLayout+ className="px-5"+ layout="horizontal"+ label="Enabled mode"+ description="Determines if a trigger should or should not fire. Can also be used to disable a trigger, but not delete it."+ >+ <FormControl_Shadcn_>+ <Select_Shadcn_ defaultValue={field.value} onValueChange={field.onChange}>+ <SelectTrigger_Shadcn_ className="col-span-8">+ {+ TRIGGER_ENABLED_MODES.find((option) => option.value === field.value)+ ?.label+ }+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ {TRIGGER_ENABLED_MODES.map((option) => (+ <SelectItem_Shadcn_ key={option.value} value={option.value}>+ <p className="text-foreground">{option.label}</p>+ <p className="text-foreground-lighter">{option.description}</p>+ </SelectItem_Shadcn_>+ ))}+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ ) : (+ <>+ <Separator />++ <FormField_Shadcn_+ name="tableId"+ control={form.control}+ render={({ field }) => (+ <FormItemLayout+ className="px-5"+ layout="horizontal"+ label="Table"+ description="Trigger will watch for changes on this table"+ >+ <FormControl_Shadcn_>+ <Select_Shadcn_+ defaultValue={field.value}+ onValueChange={(val) => {+ const table = tables.find((x) => x.id.toString() === val)+ if (table) {+ form.setValue('table', table.name)+ form.setValue('schema', table.schema)+ }+ }}+ >+ <SelectTrigger_Shadcn_ className="col-span-8">+ <SelectValue_Shadcn_ />+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ {tables.map((table) => (+ <SelectItem_Shadcn_ key={table.id} value={table.id.toString()}>+ <span className="text-foreground-light">{table.schema}.</span>+ <span className="text-foreground">{table.name}</span>+ </SelectItem_Shadcn_>+ ))}+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <FormField_Shadcn_+ name="events"+ control={form.control}+ render={() => (+ <FormItemLayout+ className="px-5"+ layout="horizontal"+ label="Events"+ description="These are the events that are watched by the trigger, only the events selected above will fire the trigger on the table you've selected."+ >+ {TRIGGER_EVENTS.map((event) => (+ <FormField_Shadcn_+ key={event.value}+ control={form.control}+ name="events"+ render={({ field }) => (+ <FormItemLayout+ hideMessage+ layout="flex"+ label={event.label}+ description={event.description}+ >+ <FormControl_Shadcn_>+ <Checkbox_Shadcn_+ className="translate-y-[2px]"+ checked={field.value?.includes(event.value)}+ onCheckedChange={(checked) => {+ return checked+ ? field.onChange([...field.value, event.value])+ : field.onChange(+ field.value?.filter((value) => value !== event.value)+ )+ }}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ ))}+ </FormItemLayout>+ )}+ />++ <FormField_Shadcn_+ name="activation"+ control={form.control}+ render={({ field }) => (+ <FormItemLayout+ className="px-5"+ layout="horizontal"+ label="Trigger type"+ description="Determines when your trigger fires"+ >+ <FormControl_Shadcn_>+ <Select_Shadcn_ defaultValue={field.value} onValueChange={field.onChange}>+ <SelectTrigger_Shadcn_ className="col-span-8">+ {TRIGGER_TYPES.find((option) => option.value === field.value)?.label}+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ {TRIGGER_TYPES.map((option) => (+ <SelectItem_Shadcn_ key={option.value} value={option.value}>+ <p className="text-foreground">{option.label}</p>+ <p className="text-foreground-lighter">{option.description}</p>+ </SelectItem_Shadcn_>+ ))}+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <FormField_Shadcn_+ name="orientation"+ control={form.control}+ render={({ field }) => (+ <FormItemLayout+ className="px-5"+ layout="horizontal"+ label="Orientation"+ description="Identifies whether the trigger fires once for each processed row or once for each statement"+ >+ <FormControl_Shadcn_>+ <Select_Shadcn_ defaultValue={field.value} onValueChange={field.onChange}>+ <SelectTrigger_Shadcn_ className="col-span-8">+ {+ TRIGGER_ORIENTATIONS.find((option) => option.value === field.value)+ ?.label+ }+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ {TRIGGER_ORIENTATIONS.map((option) => (+ <SelectItem_Shadcn_ key={option.value} value={option.value}>+ <p className="text-foreground">{option.label}</p>+ <p className="text-foreground-lighter">{option.description}</p>+ </SelectItem_Shadcn_>+ ))}+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <Separator />++ <div className="px-5 flex flex-col gap-y-2">+ <p className="text-smn">Function to trigger</p>+ {function_name.length === 0 ? (+ <button+ type="button"+ className={cn(+ 'relative w-full rounded border border-default',+ 'bg-surface-200 px-5 py-1 shadow-sm transition-all',+ 'hover:border-strong hover:bg-overlay-hover'+ )}+ onClick={() => setShowFunctionSelector(true)}+ >+ <FormBoxEmpty+ icon={<Terminal size={14} strokeWidth={2} />}+ text="Choose a function to trigger"+ />+ </button>+ ) : (+ <div+ className={cn(+ 'relative w-full flex items-center justify-between',+ 'space-x-3 px-5 py-4 border border-default',+ 'rounded shadow-sm transition-shadow'+ )}+ >+ <div className="flex items-center gap-2">+ <div className="flex h-6 w-6 items-center justify-center rounded bg-foreground text-background focus-within:bg-opacity-10">+ <Terminal size="18" strokeWidth={2} width={14} />+ </div>+ <p>+ <span className="text-sm text-foreground-light">{function_schema}</span>+ .<span className="text-sm text-foreground">{function_name}</span>+ </p>+ </div>+ <Button type="default" onClick={() => setShowFunctionSelector(true)}>+ Change function+ </Button>+ </div>+ )}+ </div>+ </>+ )}+ </form>+ </Form_Shadcn_>++ <SheetFooter className="shrink-0">+ <Button+ type="default"+ htmlType="reset"+ disabled={isCreating || isUpdating}+ onClick={() => setOpen(false)}+ >+ Cancel+ </Button>+ <Button form={formId} htmlType="submit" loading={isCreating || isUpdating}>+ Create trigger+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>++ <ChooseFunctionForm+ visible={showFunctionSelector}+ setVisible={setShowFunctionSelector}+ onChange={(fn) => {+ form.setValue('function_name', fn.name)+ form.setValue('function_schema', fn.schema)+ }}+ />+ </>+ )+}diff --git a/apps/studio/components/interfaces/Database/Triggers/Triggers.constants.ts b/apps/studio/components/interfaces/Database/Triggers/Triggers.constants.tsnew file mode 100644index 00000000000..d0e194b9483--- /dev/null+++ b/apps/studio/components/interfaces/Database/Triggers/Triggers.constants.ts@@ -0,0 +1,46 @@+export const TRIGGER_EVENTS = [+ { value: 'INSERT', label: 'Insert', description: 'Any insert operation on the table' },+ {+ value: 'UPDATE',+ label: 'Update',+ description: 'Any update operation of any column on the table',+ },+ { value: 'DELETE', label: 'Delete', description: 'Any delete operation of a record' },+]++export const TRIGGER_TYPES = [+ {+ value: 'BEFORE',+ label: 'Before the event',+ description: 'Trigger fires before the operation is attempted',+ },+ {+ value: 'AFTER',+ label: 'After the event',+ description: 'Trigger fires before the operation has completed',+ },+]++export const TRIGGER_ORIENTATIONS = [+ {+ value: 'ROW',+ label: 'Row',+ description: 'Fires once for each processed row',+ },+ {+ value: 'STATEMENT',+ label: 'Statement',+ description: 'Fires once for each statement',+ },+]++export const TRIGGER_ENABLED_MODES = [+ { value: 'ORIGIN', label: 'Origin', description: 'This is the default behaviour' },+ {+ value: 'REPLICA',+ label: 'Replica',+ description: 'Will only fire if the session is in "replica" mode',+ },+ { value: 'ALWAYS', label: 'Always', description: 'Will fire regardless of the replication role' },+ { value: 'DISABLED', label: 'Disabled', description: 'Will not fire' },+]diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsxindex b7cc7a9c27f..0097ecc6907 100644--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx@@ -1,6 +1,7 @@+import { PostgresTrigger } from '@supabase/postgres-meta'import { PermissionAction } from '@supabase/shared-types/out/constants'import { noop, partition } from 'lodash'-import { Search } from 'lucide-react'+import { Plus, Search } from 'lucide-react'import { useState } from 'react'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'@@ -23,8 +24,8 @@ import TriggerList from './TriggerList'interface TriggersListProps {createTrigger: () => void- editTrigger: (trigger: any) => void- deleteTrigger: (trigger: any) => void+ editTrigger: (trigger: PostgresTrigger) => void+ deleteTrigger: (trigger: PostgresTrigger) => void}const TriggersList = ({@@ -111,6 +112,7 @@ const TriggersList = ({<div className="flex items-center gap-x-2"><ButtonTooltipdisabled={!canCreateTriggers}+ icon={<Plus />}onClick={() => createTrigger()}className="flex-grow"tooltip={{@@ -122,8 +124,9 @@ const TriggersList = ({},}}>- Create a new trigger+ New trigger</ButtonTooltip>+<ButtonTooltiptype="default"disabled={!canCreateTriggers}diff --git a/apps/studio/components/interfaces/Database/index.ts b/apps/studio/components/interfaces/Database/index.tsindex f5d62dac764..0667d17b0dc 100644--- a/apps/studio/components/interfaces/Database/index.ts+++ b/apps/studio/components/interfaces/Database/index.ts@@ -10,9 +10,6 @@ export { default as PublicationsTables } from './Publications/PublicationsTablesexport { default as BackupsList } from './Backups/BackupsList'-export { default as CreateTrigger } from './Triggers/CreateTrigger'-export { default as DeleteTrigger } from './Triggers/DeleteTrigger'-export { default as CreateFunction } from './Functions/CreateFunction'export { default as DeleteFunction } from './Functions/DeleteFunction'diff --git a/apps/studio/pages/project/[ref]/database/triggers.tsx b/apps/studio/pages/project/[ref]/database/triggers.tsxindex 8d331386990..890b49919cd 100644--- a/apps/studio/pages/project/[ref]/database/triggers.tsx+++ b/apps/studio/pages/project/[ref]/database/triggers.tsx@@ -1,26 +1,29 @@+import { PostgresTrigger } from '@supabase/postgres-meta'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useState } from 'react'-import { CreateTrigger, DeleteTrigger } from 'components/interfaces/Database'-import TriggersList from 'components/interfaces/Database/Triggers/TriggersList/TriggersList'+import { useIsInlineEditorEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'+import { DeleteTrigger } from 'components/interfaces/Database/Triggers/DeleteTrigger'+import { TriggerSheet } from 'components/interfaces/Database/Triggers/TriggerSheet'import { generateTriggerCreateSQL } from 'components/interfaces/Database/Triggers/TriggersList/TriggerList.utils'+import TriggersList from 'components/interfaces/Database/Triggers/TriggersList/TriggersList'import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'+import DefaultLayout from 'components/layouts/DefaultLayout'import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'import { FormHeader } from 'components/ui/Forms/FormHeader'import NoPermission from 'components/ui/NoPermission'import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'-import type { NextPageWithLayout } from 'types'-import DefaultLayout from 'components/layouts/DefaultLayout'-import { useIsInlineEditorEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { useAppStateSnapshot } from 'state/app-state'+import type { NextPageWithLayout } from 'types'const TriggersPage: NextPageWithLayout = () => {- const [selectedTrigger, setSelectedTrigger] = useState<any>()- const [showCreateTriggerForm, setShowCreateTriggerForm] = useState<boolean>(false)- const [showDeleteTriggerForm, setShowDeleteTriggerForm] = useState<boolean>(false)const { setEditorPanel } = useAppStateSnapshot()const isInlineEditorEnabled = useIsInlineEditorEnabled()+ const [selectedTrigger, setSelectedTrigger] = useState<PostgresTrigger>()+ const [showCreateTriggerForm, setShowCreateTriggerForm] = useState<boolean>(false)+ const [showDeleteTriggerForm, setShowDeleteTriggerForm] = useState<boolean>(false)+const canReadTriggers = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'triggers')const isPermissionsLoaded = usePermissionsLoaded()@@ -42,7 +45,7 @@ execute function function_name();`,}}- const editTrigger = (trigger: any) => {+ const editTrigger = (trigger: PostgresTrigger) => {if (isInlineEditorEnabled) {const sql = generateTriggerCreateSQL(trigger)setEditorPanel({@@ -58,7 +61,7 @@ execute function function_name();`,}}- const deleteTrigger = (trigger: any) => {+ const deleteTrigger = (trigger: PostgresTrigger) => {setSelectedTrigger(trigger)setShowDeleteTriggerForm(true)}@@ -85,10 +88,10 @@ execute function function_name();`,</div></ScaffoldSection></ScaffoldContainer>- <CreateTrigger- trigger={selectedTrigger}- visible={showCreateTriggerForm}- setVisible={setShowCreateTriggerForm}+ <TriggerSheet+ selectedTrigger={selectedTrigger}+ open={showCreateTriggerForm}+ setOpen={setShowCreateTriggerForm}/><DeleteTriggertrigger={selectedTrigger}