TriggerSheet.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. import { zodResolver } from '@hookform/resolvers/zod'
  2. import type { PGTrigger } from '@supabase/pg-meta'
  3. import { Terminal } from 'lucide-react'
  4. import { useEffect, useState } from 'react'
  5. import { SubmitHandler, useForm } from 'react-hook-form'
  6. import { toast } from 'sonner'
  7. import {
  8. Button,
  9. Checkbox,
  10. cn,
  11. Form,
  12. FormControl,
  13. FormField,
  14. Input,
  15. Select,
  16. SelectContent,
  17. SelectItem,
  18. SelectTrigger,
  19. SelectValue,
  20. Separator,
  21. Sheet,
  22. SheetContent,
  23. SheetFooter,
  24. SheetHeader,
  25. SheetTitle,
  26. } from 'ui'
  27. import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
  28. import * as z from 'zod'
  29. import ChooseFunctionForm from './ChooseFunctionForm'
  30. import {
  31. TRIGGER_ENABLED_MODES,
  32. TRIGGER_EVENTS,
  33. TRIGGER_ORIENTATIONS,
  34. TRIGGER_TYPES,
  35. } from './Triggers.constants'
  36. import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
  37. import FormBoxEmpty from '@/components/ui/FormBoxEmpty'
  38. import { useDatabaseTriggerCreateMutation } from '@/data/database-triggers/database-trigger-create-mutation'
  39. import { useDatabaseTriggerUpdateMutation } from '@/data/database-triggers/database-trigger-update-mutation'
  40. import { useTablesQuery } from '@/data/tables/tables-query'
  41. import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
  42. import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
  43. import { useProtectedSchemas } from '@/hooks/useProtectedSchemas'
  44. const formId = 'create-trigger'
  45. const FormSchema = z.object({
  46. name: z
  47. .string()
  48. .min(1, 'Please provide a name for your trigger')
  49. .regex(/^\S+$/, 'Name should not contain spaces or whitespaces'),
  50. schema: z.string(),
  51. table: z.string(),
  52. activation: z.enum(['BEFORE', 'AFTER', 'INSTEAD OF']),
  53. enabled_mode: z.enum(['ORIGIN', 'REPLICA', 'ALWAYS', 'DISABLED']),
  54. orientation: z.enum(['ROW', 'STATEMENT']),
  55. function_name: z.string().min(1, 'Please select a database function for your trigger to call'),
  56. function_schema: z.string(),
  57. events: z.array(z.string()).min(1, 'Please select at least one event'),
  58. // For UI handling, not to be passed to the final request
  59. tableId: z.string().optional(),
  60. })
  61. const defaultValues: z.infer<typeof FormSchema> = {
  62. name: '',
  63. schema: '',
  64. table: '',
  65. activation: 'AFTER',
  66. orientation: 'ROW',
  67. function_name: '',
  68. function_schema: '',
  69. enabled_mode: 'ORIGIN',
  70. events: [],
  71. }
  72. interface TriggerSheetProps {
  73. selectedTrigger?: PGTrigger
  74. isDuplicatingTrigger?: boolean
  75. open: boolean
  76. onClose: () => void
  77. }
  78. export const TriggerSheet = ({
  79. selectedTrigger,
  80. isDuplicatingTrigger,
  81. open,
  82. onClose,
  83. }: TriggerSheetProps) => {
  84. const { data: project } = useSelectedProjectQuery()
  85. const [showFunctionSelector, setShowFunctionSelector] = useState(false)
  86. const { mutate: createDatabaseTrigger, isPending: isCreating } = useDatabaseTriggerCreateMutation(
  87. {
  88. onSuccess: () => {
  89. toast.success(`Successfully created trigger`)
  90. onClose()
  91. },
  92. onError: (error) => {
  93. toast.error(`Failed to create trigger: ${error.message}`)
  94. },
  95. }
  96. )
  97. const { mutate: updateDatabaseTrigger, isPending: isUpdating } = useDatabaseTriggerUpdateMutation(
  98. {
  99. onSuccess: () => {
  100. toast.success(`Successfully updated trigger`)
  101. onClose()
  102. },
  103. onError: (error) => {
  104. toast.error(`Failed to update trigger: ${error.message}`)
  105. },
  106. }
  107. )
  108. const { data = [], isSuccess: isSuccessTables } = useTablesQuery({
  109. projectRef: project?.ref,
  110. connectionString: project?.connectionString,
  111. })
  112. const { data: protectedSchemas, isSuccess: isSuccessProtectedSchemas } = useProtectedSchemas()
  113. const isSuccess = isSuccessTables && isSuccessProtectedSchemas
  114. const tables = data
  115. .sort((a, b) => a.schema.localeCompare(b.schema))
  116. .filter((a) => !protectedSchemas.find((s) => s.name === a.schema))
  117. const isEditing = !isDuplicatingTrigger && !!selectedTrigger
  118. const form = useForm<z.infer<typeof FormSchema>>({
  119. mode: 'onSubmit',
  120. reValidateMode: 'onSubmit',
  121. resolver: zodResolver(FormSchema as any),
  122. defaultValues,
  123. })
  124. const { function_name, function_schema } = form.watch()
  125. const { confirmOnClose, handleOpenChange, modalProps } = useConfirmOnClose({
  126. checkIsDirty: () => form.formState.isDirty,
  127. onClose,
  128. })
  129. const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (values) => {
  130. if (!project) return console.error('Project is required')
  131. const { tableId, ...payload } = values
  132. if (isEditing) {
  133. updateDatabaseTrigger({
  134. projectRef: project?.ref,
  135. connectionString: project?.connectionString,
  136. originalTrigger: selectedTrigger,
  137. payload: { name: payload.name, enabled_mode: payload.enabled_mode },
  138. })
  139. } else {
  140. createDatabaseTrigger({
  141. projectRef: project?.ref,
  142. connectionString: project?.connectionString,
  143. payload,
  144. })
  145. }
  146. }
  147. useEffect(() => {
  148. if (open && isSuccess) {
  149. form.clearErrors()
  150. if (isDuplicatingTrigger && selectedTrigger) {
  151. const initalSelectedTable = tables.find((t) => t.name === selectedTrigger.table)
  152. form.reset({
  153. ...selectedTrigger,
  154. tableId: initalSelectedTable?.id.toString(),
  155. table: initalSelectedTable?.name,
  156. schema: initalSelectedTable?.schema,
  157. })
  158. } else if (isEditing) {
  159. form.reset(selectedTrigger)
  160. } else if (tables.length > 0) {
  161. form.reset({
  162. ...defaultValues,
  163. tableId: tables[0].id.toString(),
  164. table: tables[0].name,
  165. schema: tables[0].schema,
  166. })
  167. }
  168. }
  169. // eslint-disable-next-line react-hooks/exhaustive-deps
  170. }, [open, isSuccess])
  171. return (
  172. <>
  173. <Sheet open={open} onOpenChange={handleOpenChange}>
  174. <SheetContent size="lg" className="flex flex-col gap-0">
  175. <SheetHeader>
  176. <SheetTitle>
  177. {isDuplicatingTrigger
  178. ? 'Duplicate trigger'
  179. : isEditing
  180. ? `Edit database trigger: ${selectedTrigger.name}`
  181. : 'Create a new database trigger'}
  182. </SheetTitle>
  183. </SheetHeader>
  184. <Form {...form}>
  185. <form
  186. id={formId}
  187. className="flex-1 flex flex-col gap-y-6 overflow-auto py-6"
  188. onSubmit={form.handleSubmit(onSubmit)}
  189. >
  190. <FormField
  191. name="name"
  192. control={form.control}
  193. render={({ field }) => (
  194. <FormItemLayout
  195. className="px-5"
  196. layout="horizontal"
  197. label="Name of trigger"
  198. description="Do not use spaces/whitespace."
  199. >
  200. <FormControl>
  201. <Input {...field} placeholder="Name of trigger" />
  202. </FormControl>
  203. </FormItemLayout>
  204. )}
  205. />
  206. {isEditing ? (
  207. <FormField
  208. name="enabled_mode"
  209. control={form.control}
  210. render={({ field }) => (
  211. <FormItemLayout
  212. className="px-5"
  213. layout="horizontal"
  214. label="Enabled mode"
  215. description="Determines if a trigger should or should not fire. Can also be used to disable a trigger, but not delete it."
  216. >
  217. <FormControl>
  218. <Select defaultValue={field.value} onValueChange={field.onChange}>
  219. <SelectTrigger className="col-span-8">
  220. {
  221. TRIGGER_ENABLED_MODES.find((option) => option.value === field.value)
  222. ?.label
  223. }
  224. </SelectTrigger>
  225. <SelectContent>
  226. {TRIGGER_ENABLED_MODES.map((option) => (
  227. <SelectItem key={option.value} value={option.value}>
  228. <p className="text-foreground">{option.label}</p>
  229. <p className="text-foreground-lighter">{option.description}</p>
  230. </SelectItem>
  231. ))}
  232. </SelectContent>
  233. </Select>
  234. </FormControl>
  235. </FormItemLayout>
  236. )}
  237. />
  238. ) : (
  239. <>
  240. <Separator />
  241. <FormField
  242. name="tableId"
  243. control={form.control}
  244. render={({ field }) => (
  245. <FormItemLayout
  246. className="px-5"
  247. layout="horizontal"
  248. label="Table"
  249. description="Trigger will watch for changes on this table"
  250. >
  251. <FormControl>
  252. <Select
  253. defaultValue={field.value}
  254. onValueChange={(val) => {
  255. // mark table ID as dirty to trigger validation
  256. field.onChange(val)
  257. const table = tables.find((x) => x.id.toString() === val)
  258. if (table) {
  259. form.setValue('table', table.name, { shouldDirty: true })
  260. form.setValue('schema', table.schema, { shouldDirty: true })
  261. }
  262. }}
  263. >
  264. <SelectTrigger className="col-span-8">
  265. <SelectValue />
  266. </SelectTrigger>
  267. <SelectContent>
  268. {tables.map((table) => (
  269. <SelectItem key={table.id} value={table.id.toString()}>
  270. <span className="text-foreground-light">{table.schema}.</span>
  271. <span className="text-foreground">{table.name}</span>
  272. </SelectItem>
  273. ))}
  274. </SelectContent>
  275. </Select>
  276. </FormControl>
  277. </FormItemLayout>
  278. )}
  279. />
  280. <FormField
  281. name="events"
  282. control={form.control}
  283. render={() => (
  284. <FormItemLayout
  285. className="px-5"
  286. layout="horizontal"
  287. label="Events"
  288. 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."
  289. >
  290. {TRIGGER_EVENTS.map((event) => (
  291. <FormField
  292. key={event.value}
  293. control={form.control}
  294. name="events"
  295. render={({ field }) => (
  296. <FormItemLayout
  297. hideMessage
  298. layout="flex"
  299. label={event.label}
  300. description={event.description}
  301. >
  302. <FormControl>
  303. <Checkbox
  304. className="translate-y-[2px]"
  305. checked={field.value?.includes(event.value)}
  306. onCheckedChange={(checked) => {
  307. return checked
  308. ? field.onChange([...field.value, event.value])
  309. : field.onChange(
  310. field.value?.filter((value) => value !== event.value)
  311. )
  312. }}
  313. />
  314. </FormControl>
  315. </FormItemLayout>
  316. )}
  317. />
  318. ))}
  319. </FormItemLayout>
  320. )}
  321. />
  322. <FormField
  323. name="activation"
  324. control={form.control}
  325. render={({ field }) => (
  326. <FormItemLayout
  327. className="px-5"
  328. layout="horizontal"
  329. label="Trigger type"
  330. description="Determines when your trigger fires"
  331. >
  332. <FormControl>
  333. <Select defaultValue={field.value} onValueChange={field.onChange}>
  334. <SelectTrigger className="col-span-8">
  335. {TRIGGER_TYPES.find((option) => option.value === field.value)?.label}
  336. </SelectTrigger>
  337. <SelectContent>
  338. {TRIGGER_TYPES.map((option) => (
  339. <SelectItem key={option.value} value={option.value}>
  340. <p className="text-foreground">{option.label}</p>
  341. <p className="text-foreground-lighter">{option.description}</p>
  342. </SelectItem>
  343. ))}
  344. </SelectContent>
  345. </Select>
  346. </FormControl>
  347. </FormItemLayout>
  348. )}
  349. />
  350. <FormField
  351. name="orientation"
  352. control={form.control}
  353. render={({ field }) => (
  354. <FormItemLayout
  355. className="px-5"
  356. layout="horizontal"
  357. label="Orientation"
  358. description="Identifies whether the trigger fires once for each processed row or once for each statement"
  359. >
  360. <FormControl>
  361. <Select defaultValue={field.value} onValueChange={field.onChange}>
  362. <SelectTrigger className="col-span-8">
  363. {
  364. TRIGGER_ORIENTATIONS.find((option) => option.value === field.value)
  365. ?.label
  366. }
  367. </SelectTrigger>
  368. <SelectContent>
  369. {TRIGGER_ORIENTATIONS.map((option) => (
  370. <SelectItem key={option.value} value={option.value}>
  371. <p className="text-foreground">{option.label}</p>
  372. <p className="text-foreground-lighter">{option.description}</p>
  373. </SelectItem>
  374. ))}
  375. </SelectContent>
  376. </Select>
  377. </FormControl>
  378. </FormItemLayout>
  379. )}
  380. />
  381. <Separator />
  382. <FormField
  383. name="function_name"
  384. control={form.control}
  385. render={() => (
  386. <FormItemLayout layout="vertical" className="px-5">
  387. <FormControl>
  388. <div className="flex flex-col gap-y-2">
  389. <p className="text-sm">Function to trigger</p>
  390. {function_name.length === 0 ? (
  391. <button
  392. type="button"
  393. className={cn(
  394. 'relative w-full rounded-sm border border-default',
  395. 'bg-surface-200 px-5 py-1 shadow-xs transition-all',
  396. 'hover:border-strong hover:bg-overlay-hover'
  397. )}
  398. onClick={() => setShowFunctionSelector(true)}
  399. >
  400. <FormBoxEmpty
  401. icon={<Terminal size={14} strokeWidth={2} />}
  402. text="Choose a function to trigger"
  403. />
  404. </button>
  405. ) : (
  406. <div
  407. className={cn(
  408. 'relative w-full flex items-center justify-between',
  409. 'space-x-3 px-5 py-4 border border-default',
  410. 'rounded-sm shadow-xs transition-shadow'
  411. )}
  412. >
  413. <div className="flex items-center gap-2">
  414. <div className="flex h-6 w-6 items-center justify-center rounded-sm bg-foreground text-background focus-within:bg-foreground/10">
  415. <Terminal size="18" strokeWidth={2} width={14} />
  416. </div>
  417. <p>
  418. <span className="text-sm text-foreground-light">
  419. {function_schema}
  420. </span>
  421. .
  422. <span className="text-sm text-foreground">{function_name}</span>
  423. </p>
  424. </div>
  425. <Button
  426. type="default"
  427. onClick={() => setShowFunctionSelector(true)}
  428. >
  429. Change function
  430. </Button>
  431. </div>
  432. )}
  433. </div>
  434. </FormControl>
  435. </FormItemLayout>
  436. )}
  437. />
  438. </>
  439. )}
  440. </form>
  441. </Form>
  442. <SheetFooter className="shrink-0">
  443. <Button
  444. type="default"
  445. htmlType="reset"
  446. disabled={isCreating || isUpdating}
  447. onClick={confirmOnClose}
  448. >
  449. Cancel
  450. </Button>
  451. <Button form={formId} htmlType="submit" loading={isCreating || isUpdating}>
  452. {isEditing ? 'Save' : 'Create'} trigger
  453. </Button>
  454. </SheetFooter>
  455. <DiscardChangesConfirmationDialog {...modalProps} />
  456. </SheetContent>
  457. </Sheet>
  458. <ChooseFunctionForm
  459. visible={showFunctionSelector}
  460. setVisible={setShowFunctionSelector}
  461. onChange={(fn) => {
  462. form.setValue('function_name', fn.name, { shouldDirty: true })
  463. form.setValue('function_schema', fn.schema, { shouldDirty: true })
  464. }}
  465. />
  466. </>
  467. )
  468. }