Skip to content

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

feat: UI for pg-cron (#29291)

Ivan Vasilovfd3309c8861c
diff --git a/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
index 14177c0914b..6a3275c5643 100644
--- a/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
+++ b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
@@ -8,8 +8,10 @@ import { toast } from 'sonner'
import * as z from 'zod'
import { useParams } from 'common'
+import { convertArgumentTypes } from 'components/interfaces/Database/Functions/Functions.utils'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import CodeEditor from 'components/ui/CodeEditor/CodeEditor'
+import FunctionSelector from 'components/ui/FunctionSelector'
import SchemaSelector from 'components/ui/SchemaSelector'
import { AuthConfigResponse } from 'data/auth/auth-config-query'
import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'
@@ -34,7 +36,6 @@ import {
cn,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-import FunctionSelector from './FunctionSelector'
import { HOOKS_DEFINITIONS, HOOK_DEFINITION_TITLE, Hook } from './hooks.constants'
import { extractMethod, getRevokePermissionStatements, isValidHook } from './hooks.utils'
@@ -392,6 +393,21 @@ export const CreateHookSheet = ({
value={field.value}
onChange={field.onChange}
disabled={field.disabled}
+ filterFunction={(func) => {
+ if (func.return_type === 'json' || func.return_type === 'jsonb') {
+ const { value } = convertArgumentTypes(func.argument_types)
+ if (value.length !== 1) return false
+ return value[0].type === 'json' || value[0].type === 'jsonb'
+ }
+ return false
+ }}
+ noResultsLabel={
+ <span>
+ No function with a single JSON/B argument
+ <br />
+ and JSON/B return type found in this schema.
+ </span>
+ }
/>
</FormControl_Shadcn_>
</FormItemLayout>
diff --git a/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx b/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx
index b38c0f43d84..38e78f349cc 100644
--- a/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx
+++ b/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx
@@ -1,6 +1,8 @@
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { Check, Webhook } from 'lucide-react'
import { Badge, Input } from 'ui'
+
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { copyToClipboard } from 'lib/helpers'
import { Hook } from './hooks.constants'
interface HookCardProps {
@@ -35,7 +37,9 @@ export const HookCard = ({ hook, canUpdateConfig, onToggle, onSelect }: HookCard
disabled
className="input-mono [&>div>div>div>input]:text-xs [&>div>div>div>input]:opacity-100 flex-1"
value={hook.method.schema}
- onCopy={() => {}}
+ onCopy={() =>
+ hook.method.type === 'postgres' && copyToClipboard(hook.method.schema)
+ }
/>
</div>
<div className="flex flex-row items-center">
@@ -47,7 +51,9 @@ export const HookCard = ({ hook, canUpdateConfig, onToggle, onSelect }: HookCard
disabled
className="input-mono [&>div>div>div>input]:text-xs [&>div>div>div>input]:opacity-100 flex-1"
value={hook.method.functionName}
- onCopy={() => {}}
+ onCopy={() =>
+ hook.method.type === 'postgres' && copyToClipboard(hook.method.functionName)
+ }
/>
</div>
</div>
@@ -66,7 +72,7 @@ export const HookCard = ({ hook, canUpdateConfig, onToggle, onSelect }: HookCard
disabled
className="input-mono [&>div>div>div>input]:text-xs [&>div>div>div>input]:opacity-100 flex-1"
value={hook.method.url}
- onCopy={() => {}}
+ onCopy={() => hook.method.type === 'https' && copyToClipboard(hook.method.url)}
/>
</div>
<div className="flex flex-row items-center">
diff --git a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/AddRLSPolicyForFirebaseDialog.tsx b/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/AddRLSPolicyForFirebaseDialog.tsx
index f1c2d25a0a5..3f98c84a003 100644
--- a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/AddRLSPolicyForFirebaseDialog.tsx
+++ b/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/AddRLSPolicyForFirebaseDialog.tsx
@@ -58,7 +58,7 @@ export const AddRLSPolicyForFirebaseDialog = ({
</DialogHeader>
<DialogSectionSeparator />
<DialogSection padding={'small'}>
- <SQLCodeBlock projectRef={projectRef!}>{[description]}</SQLCodeBlock>
+ <SQLCodeBlock>{[description]}</SQLCodeBlock>
</DialogSection>
<DialogFooter padding={'small'}>
<Button
diff --git a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/SqlCodeBlock.tsx b/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/SqlCodeBlock.tsx
index 31a62fa0486..c0afb0d5e71 100644
--- a/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/SqlCodeBlock.tsx
+++ b/apps/studio/components/interfaces/Auth/ThirdPartyAuthForm/SqlCodeBlock.tsx
@@ -3,10 +3,10 @@ import { CodeBlock, cn } from 'ui'
interface SQLCodeBlockProps {
children: string[]
- projectRef: string
+ className?: string
}
-export const SQLCodeBlock = ({ children }: SQLCodeBlockProps) => {
+export const SQLCodeBlock = ({ children, className }: SQLCodeBlockProps) => {
let formatted = (children || [''])[0]
try {
formatted = format(formatted, {
@@ -25,10 +25,11 @@ export const SQLCodeBlock = ({ children }: SQLCodeBlockProps) => {
value={formatted}
language="sql"
className={cn(
- '!py-3 !px-3.5 prose dark:prose-dark transition max-w-full',
+ 'py-3 px-3.5 prose dark:prose-dark transition max-w-full',
// change the look of the code block. The flex hack is so that the code is wrapping since
// every word is a separate span
- '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap'
+ '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap',
+ className
)}
hideCopy
hideLineNumbers
diff --git a/apps/studio/components/interfaces/Database/CronJobs/CreateCronJobSheet.tsx b/apps/studio/components/interfaces/Database/CronJobs/CreateCronJobSheet.tsx
new file mode 100644
index 00000000000..964bb8b840a
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/CreateCronJobSheet.tsx
@@ -0,0 +1,396 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { toString as CronToString } from 'cronstrue'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import { toast } from 'sonner'
+import z from 'zod'
+
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { urlRegex } from 'components/interfaces/Auth/Auth.constants'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { useDatabaseCronJobCreateMutation } from 'data/database-cron-jobs/database-cron-jobs-create-mutation'
+import { CronJob } from 'data/database-cron-jobs/database-cron-jobs-query'
+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useState } from 'react'
+import {
+ Button,
+ Form_Shadcn_,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ Input_Shadcn_,
+ RadioGroupStacked,
+ RadioGroupStackedItem,
+ Separator,
+ SheetFooter,
+ SheetHeader,
+ SheetSection,
+ SheetTitle,
+ WarningIcon,
+} from 'ui'
+import { Admonition } from 'ui-patterns'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import EnableExtensionModal from '../Extensions/EnableExtensionModal'
+import { CRONJOB_DEFINITIONS } from './CronJobs.constants'
+import { buildCronQuery, buildHttpRequestCommand, parseCronJobCommand } from './CronJobs.utils'
+import { CronJobScheduleSection } from './CronJobScheduleSection'
+import { EdgeFunctionSection } from './EdgeFunctionSection'
+import { HTTPHeaderFieldsSection } from './HttpHeaderFieldsSection'
+import { HTTPParameterFieldsSection } from './HttpParameterFieldsSection'
+import { HttpRequestSection } from './HttpRequestSection'
+import { SqlFunctionSection } from './SqlFunctionSection'
+import { SqlSnippetSection } from './SqlSnippetSection'
+
+export interface CreateCronJobSheetProps {
+ selectedCronJob?: Pick<CronJob, 'jobname' | 'schedule' | 'active' | 'command'>
+ isClosing: boolean
+ setIsClosing: (v: boolean) => void
+ onClose: () => void
+}
+
+const edgeFunctionSchema = z.object({
+ type: z.literal('edge_function'),
+ method: z.enum(['GET', 'POST']),
+ edgeFunctionName: z.string().trim().min(1, 'Please select one of the listed Edge Functions'),
+ timeoutMs: z.coerce.number().int().gte(1000).lte(5000).default(1000),
+ httpHeaders: z.array(z.object({ name: z.string(), value: z.string() })),
+ httpParameters: z.array(z.object({ name: z.string(), value: z.string() })),
+})
+
+const httpRequestSchema = z.object({
+ type: z.literal('http_request'),
+ method: z.enum(['GET', 'POST']),
+ endpoint: z
+ .string()
+ .trim()
+ .min(1, 'Please provide a URL')
+ .regex(urlRegex, 'Please provide a valid URL')
+ .refine((value) => value.startsWith('http'), 'Please include HTTP/HTTPs to your URL'),
+ timeoutMs: z.coerce.number().int().gte(1000).lte(5000).default(1000),
+ httpHeaders: z.array(z.object({ name: z.string(), value: z.string() })),
+ httpParameters: z.array(z.object({ name: z.string(), value: z.string() })),
+})
+
+const sqlFunctionSchema = z.object({
+ type: z.literal('sql_function'),
+ schema: z.string().trim().min(1, 'Please select one of the listed database schemas'),
+ functionName: z.string().trim().min(1, 'Please select one of the listed database functions'),
+})
+const sqlSnippetSchema = z.object({
+ type: z.literal('sql_snippet'),
+ snippet: z.string().trim().min(1),
+})
+
+const FormSchema = z.object({
+ name: z.string().trim().min(1, 'Please provide a name for your cron job'),
+ schedule: z
+ .string()
+ .trim()
+ .min(1)
+ .refine((value) => {
+ try {
+ CronToString(value)
+ } catch {
+ return false
+ }
+ return true
+ }, 'The schedule needs to be in a Cron format.'),
+ values: z.discriminatedUnion('type', [
+ edgeFunctionSchema,
+ httpRequestSchema,
+ sqlFunctionSchema,
+ sqlSnippetSchema,
+ ]),
+})
+
+export type CreateCronJobForm = z.infer<typeof FormSchema>
+export type CronJobType = CreateCronJobForm['values']
+
+const FORM_ID = 'create-cron-job-sidepanel'
+
+export const CreateCronJobSheet = ({
+ selectedCronJob,
+ isClosing,
+ setIsClosing,
+ onClose,
+}: CreateCronJobSheetProps) => {
+ const isEditing = !!selectedCronJob?.jobname
+ const [showEnableExtensionModal, setShowEnableExtensionModal] = useState(false)
+ const { mutate: upsertCronJob, isLoading } = useDatabaseCronJobCreateMutation()
+
+ const canToggleExtensions = useCheckPermissions(
+ PermissionAction.TENANT_SQL_ADMIN_WRITE,
+ 'extensions'
+ )
+
+ const cronJobValues = parseCronJobCommand(selectedCronJob?.command || '')
+
+ const form = useForm<CreateCronJobForm>({
+ resolver: zodResolver(FormSchema),
+ defaultValues: {
+ name: selectedCronJob?.jobname || '',
+ schedule: selectedCronJob?.schedule || '',
+ values: cronJobValues,
+ },
+ })
+
+ const { project } = useProjectContext()
+ const isEdited = form.formState.isDirty
+
+ // if the form hasn't been touched and the user clicked esc or the backdrop, close the sheet
+ if (!isEdited && isClosing) {
+ onClose()
+ }
+
+ const onClosePanel = () => {
+ if (isEdited) {
+ setIsClosing(true)
+ } else {
+ onClose()
+ }
+ }
+
+ const onSubmit: SubmitHandler<CreateCronJobForm> = async ({ name, schedule, values }) => {
+ let command = ''
+ if (values.type === 'edge_function') {
+ command = buildHttpRequestCommand(
+ values.method,
+ values.edgeFunctionName,
+ values.httpHeaders,
+ values.httpParameters,
+ values.timeoutMs
+ )
+ } else if (values.type === 'http_request') {
+ command = buildHttpRequestCommand(
+ values.method,
+ values.endpoint,
+ values.httpHeaders,
+ values.httpParameters,
+ values.timeoutMs
+ )
+ } else if (values.type === 'sql_function') {
+ command = `'CALL ${values.schema}.${values.functionName}()'`
+ } else {
+ command = `$$${values.snippet}$$`
+ }
+
+ const query = buildCronQuery(name, schedule, command)
+
+ upsertCronJob(
+ {
+ projectRef: project!.ref,
+ connectionString: project?.connectionString,
+ query,
+ },
+ {
+ onSuccess: () => {
+ if (isEditing) {
+ toast.success(`Successfully updated cron job ${name}`)
+ } else {
+ toast.success(`Successfully created cron job ${name}`)
+ }
+ onClose()
+ },
+ }
+ )
+ }
+
+ const { data } = useDatabaseExtensionsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const pgNetExtension = (data ?? []).find((ext) => ext.name === 'pg_net')
+ const pgNetExtensionInstalled = pgNetExtension?.installed_version != undefined
+
+ const cronType = form.watch('values.type')
+
+ return (
+ <>
+ <div className="flex flex-col h-full" tabIndex={-1}>
+ <SheetHeader>
+ <SheetTitle>
+ {isEditing ? `Edit ${selectedCronJob.jobname}` : `Create a new cron job`}
+ </SheetTitle>
+ </SheetHeader>
+
+ <div className="overflow-auto flex-grow">
+ <Form_Shadcn_ {...form}>
+ <form
+ id={FORM_ID}
+ className="flex-grow overflow-auto"
+ onSubmit={form.handleSubmit(onSubmit)}
+ >
+ <SheetSection>
+ <FormField_Shadcn_
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItemLayout label="Name" layout="vertical" className="gap-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </SheetSection>
+ <Separator />
+ <CronJobScheduleSection form={form} />
+ <Separator />
+ <SheetSection>
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.type"
+ render={({ field }) => (
+ <FormItemLayout label="Type" layout="vertical" className="gap-1">
+ <FormControl_Shadcn_>
+ <RadioGroupStacked
+ id="function_type"
+ name="function_type"
+ value={field.value}
+ disabled={field.disabled}
+ onValueChange={field.onChange}
+ >
+ {CRONJOB_DEFINITIONS.map((definition) => (
+ <RadioGroupStackedItem
+ key={definition.value}
+ id={definition.value}
+ value={definition.value}
+ disabled={
+ !pgNetExtensionInstalled &&
+ (definition.value === 'http_request' ||
+ definition.value === 'edge_function')
+ }
+ label=""
+ showIndicator={false}
+ >
+ <div className="flex items-center gap-x-5">
+ <div className="text-foreground">{definition.icon}</div>
+ <div className="flex flex-col">
+ <div className="flex gap-x-2">
+ <p className="text-foreground">{definition.label}</p>
+ </div>
+ <p className="text-foreground-light">{definition.description}</p>
+ </div>
+ </div>
+ {!pgNetExtensionInstalled &&
+ (definition.value === 'http_request' ||
+ definition.value === 'edge_function') ? (
+ <div className="w-full flex gap-x-2 pl-11 py-2 items-center">
+ <WarningIcon />
+ <span className="text-xs">
+ <code>pg_net</code> needs to be installed to use this type
+ </span>
+ </div>
+ ) : null}
+ </RadioGroupStackedItem>
+ ))}
+ </RadioGroupStacked>
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ {!pgNetExtensionInstalled && (
+ <Admonition
+ type="note"
+ // @ts-ignore
+ title={
+ <span>
+ Enable <code className="text-xs w-min">pg_net</code> for HTTP requests or
+ Edge Functions
+ </span>
+ }
+ description={
+ <div className="flex flex-col gap-y-2">
+ <span>
+ This will allow you to send HTTP requests or trigger an edge function
+ within your cron jobs
+ </span>
+ <ButtonTooltip
+ type="default"
+ className="w-min"
+ disabled={!canToggleExtensions}
+ onClick={() => setShowEnableExtensionModal(true)}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: 'You need additional permissions to enable database extensions',
+ },
+ }}
+ >
+ Install pg_net extension
+ </ButtonTooltip>
+ </div>
+ }
+ />
+ )}
+ </SheetSection>
+ <Separator />
+ {cronType === 'http_request' && (
+ <>
+ <HttpRequestSection form={form} />
+ <Separator />
+ <HTTPHeaderFieldsSection fieldName="values.httpHeaders" />
+ <Separator />
+ <HTTPParameterFieldsSection fieldName="values.httpParameters" />
+ </>
+ )}
+ {cronType === 'edge_function' && (
+ <>
+ <EdgeFunctionSection form={form} />
+ <Separator />
+ <HTTPHeaderFieldsSection fieldName="values.httpHeaders" />
+ <Separator />
+ <HTTPParameterFieldsSection fieldName="values.httpParameters" />
+ </>
+ )}
+ {cronType === 'sql_function' && <SqlFunctionSection form={form} />}
+ {cronType === 'sql_snippet' && <SqlSnippetSection form={form} />}
+ </form>
+ </Form_Shadcn_>
+ </div>
+ <SheetFooter>
+ <Button
+ size="tiny"
+ type="default"
+ htmlType="button"
+ onClick={onClosePanel}
+ disabled={isLoading}
+ >
+ Cancel
+ </Button>
+ <Button
+ size="tiny"
+ type="primary"
+ form={FORM_ID}
+ htmlType="submit"
+ disabled={isLoading}
+ loading={isLoading}
+ >
+ {isEditing ? `Save cron job` : 'Create cron job'}
+ </Button>
+ </SheetFooter>
+ </div>
+ <ConfirmationModal
+ visible={isClosing}
+ title="Discard changes"
+ confirmLabel="Discard"
+ onCancel={() => setIsClosing(false)}
+ onConfirm={() => onClose()}
+ >
+ <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>
+ {pgNetExtension && (
+ <EnableExtensionModal
+ visible={showEnableExtensionModal}
+ extension={pgNetExtension}
+ onCancel={() => setShowEnableExtensionModal(false)}
+ />
+ )}
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/CronJobCard.tsx b/apps/studio/components/interfaces/Database/CronJobs/CronJobCard.tsx
new file mode 100644
index 00000000000..04e3124409f
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/CronJobCard.tsx
@@ -0,0 +1,146 @@
+import { toString as CronToString } from 'cronstrue'
+import { Clock, Loader2, MoreVertical } from 'lucide-react'
+import Link from 'next/link'
+
+import { useParams } from 'common'
+import { SQLCodeBlock } from 'components/interfaces/Auth/ThirdPartyAuthForm/SqlCodeBlock'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { CronJob } from 'data/database-cron-jobs/database-cron-jobs-query'
+import { useDatabaseCronJobToggleMutation } from 'data/database-cron-jobs/database-cron-jobs-toggle-mutation'
+import { useState } from 'react'
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ Input,
+ Label_Shadcn_,
+ Switch,
+} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+
+interface CronJobCardProps {
+ job: CronJob
+ onEditCronJob: (job: CronJob) => void
+ onDeleteCronJob: (job: CronJob) => void
+}
+
+const generateJobDetailsSQL = (jobId: number) => {
+ return `select * from cron.job_run_details where jobid = '${jobId}' order by start_time desc limit 10`
+}
+
+export const CronJobCard = ({ job, onEditCronJob, onDeleteCronJob }: CronJobCardProps) => {
+ const [toggleConfirmationModalShown, showToggleConfirmationModal] = useState(false)
+ const { ref } = useParams()
+ const { project: selectedProject } = useProjectContext()
+ const { mutate: toggleDatabaseCronJob, isLoading } = useDatabaseCronJobToggleMutation()
+
+ // pg_cron can also use "30 seconds" format for schedule. Cronstrue doesn't understand that format so just use the
+ // original schedule when cronstrue throws
+ let schedule = job.schedule
+ try {
+ const scheduleString = CronToString(job.schedule)
+ schedule = scheduleString
+ } catch {}
+
+ return (
+ <>
+ <div className="bg-surface-100 border-default overflow-hidden border shadow px-5 py-4 flex flex-row rounded-md space-x-4">
+ <div>
+ <Clock size={24} className="text-foreground-muted mt-0.5" />
+ </div>
+ <div className="flex flex-col flex-0 overflow-y-auto w-full">
+ <div className="flex flex-row justify-between items-center">
+ <span className="text-base text-foreground">{job.jobname}</span>
+ <div className="flex items-center gap-x-2">
+ {isLoading ? (
+ <Loader2 size={18} strokeWidth={2} className="animate-spin text-foreground-muted" />
+ ) : (
+ <Label_Shadcn_
+ htmlFor={`cron-job-active-${job.jobid}`}
+ className="text-foreground-light text-xs"
+ >
+ {job.active ? 'Active' : 'Inactive'}
+ </Label_Shadcn_>
+ )}
+ <Switch
+ id={`cron-job-active-${job.jobid}`}
+ size="large"
+ disabled={isLoading}
+ checked={job.active}
+ onCheckedChange={() => showToggleConfirmationModal(true)}
+ />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="default" icon={<MoreVertical />} className="px-1.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-36">
+ <DropdownMenuItem asChild>
+ <Link
+ href={`/project/${ref}/sql/new?content=${encodeURIComponent(generateJobDetailsSQL(job.jobid))}`}
+ >
+ View previous runs
+ </Link>
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => onEditCronJob(job)}>
+ Edit cron job
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => onDeleteCronJob(job)}>
+ Delete cron job
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ <div className="text-sm flex flex-row space-x-5 py-4">
+ <div className="flex flex-col w-full space-y-2">
+ <div className="grid grid-cols-10 gap-3 items-center">
+ <span className="text-foreground-light col-span-1">Schedule</span>
+ <div className="col-span-9">
+ <Input
+ title={schedule}
+ readOnly
+ className="input-mono [&>div>div>div>input]:text-xs [&>div>div>div>input]:opacity-100 flex-1"
+ value={schedule}
+ />
+ </div>
+ </div>
+ <div className="grid grid-cols-10 gap-3">
+ <span className="text-foreground-light col-span-1">Command</span>
+ <div className="col-span-9">
+ <SQLCodeBlock className="py-2">{[job.command.trim()]}</SQLCodeBlock>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <ConfirmationModal
+ visible={toggleConfirmationModalShown}
+ title={job.active ? 'Disable cron job' : 'Enable cron job'}
+ loading={isLoading}
+ confirmLabel={job.active ? 'Disable' : 'Enable'}
+ onCancel={() => showToggleConfirmationModal(false)}
+ variant={job.active ? 'destructive' : undefined}
+ onConfirm={() => {
+ toggleDatabaseCronJob({
+ projectRef: selectedProject?.ref!,
+ connectionString: selectedProject?.connectionString,
+ jobId: job.jobid,
+ active: !job.active,
+ })
+ showToggleConfirmationModal(false)
+ }}
+ >
+ <p className="text-sm text-foreground-light">
+ <span>{`Are you sure you want to ${job.active ? 'disable' : 'enable'} the`}</span>{' '}
+ <span className="text-brand">{`${job?.jobname}`}</span>
+ <span> cron job?</span>
+ </p>
+ </ConfirmationModal>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/CronJobScheduleSection.tsx b/apps/studio/components/interfaces/Database/CronJobs/CronJobScheduleSection.tsx
new file mode 100644
index 00000000000..971dda56a86
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/CronJobScheduleSection.tsx
@@ -0,0 +1,122 @@
+import { toString as CronToString } from 'cronstrue'
+import { useEffect, useState } from 'react'
+import { UseFormReturn } from 'react-hook-form'
+
+import {
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormLabel_Shadcn_,
+ FormMessage_Shadcn_,
+ Input_Shadcn_,
+ Select_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ SheetSection,
+} from 'ui'
+import { CreateCronJobForm } from './CreateCronJobSheet'
+
+interface CronJobScheduleSectionProps {
+ form: UseFormReturn<CreateCronJobForm>
+}
+
+const schedules = [
+ { name: 'Every minute', expression: '* * * * *' },
+ { name: 'Every 5 minutes', expression: '*/5 * * * *' },
+ { name: 'Every hour, at 30 minutes', expression: '30 * * * *' },
+ { name: 'Every first of the month, at 00:00', expression: '0 0 1 * *' },
+ { name: 'Custom', expression: 'custom' },
+] as const
+
+export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) => {
+ let initialValue = schedules[0].expression as string
+ const scheduleValue = form.getValues('schedule')
+ if (scheduleValue && scheduleValue.length > 0) {
+ initialValue = 'custom'
+ }
+
+ const [presetValue, setPresetValue] = useState<string>(initialValue)
+
+ const onChangeSelectValue = (v: string) => {
+ setPresetValue(v)
+ }
+
+ useEffect(() => {
+ if (presetValue !== 'custom') {
+ form.setValue('schedule', presetValue)
+ }
+ }, [presetValue, form])
+
+ return (
+ <SheetSection>
+ <FormField_Shadcn_
+ control={form.control}
+ name="schedule"
+ render={({ field, fieldState }) => {
+ let scheduleString = ''
+ try {
+ scheduleString = CronToString(field.value)
+ } catch {}
+
+ return (
+ <FormItem_Shadcn_ className="flex flex-col gap-1">
+ <FormLabel_Shadcn_>Schedule</FormLabel_Shadcn_>
+ <FormControl_Shadcn_>
+ <div className="flex flex-col gap-2">
+ <Select_Shadcn_ onValueChange={onChangeSelectValue} value={presetValue}>
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ placeholder="Select a method for the HTTP request" />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ <SelectContent_Shadcn_>
+ {schedules.map((schedule) => {
+ return (
+ <SelectItem_Shadcn_ key={schedule.name} value={schedule.expression}>
+ {schedule.name}
+ </SelectItem_Shadcn_>
+ )
+ })}
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ disabled={field.disabled || presetValue !== 'custom'}
+ size="large"
+ autoComplete="off"
+ />
+ </div>
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ className="mt-1">
+ {scheduleString ? (
+ <span className="text-foreground-light">
+ The cron will be run {/* lowercase the first letter */}
+ {scheduleString
+ .split(' ')
+ .map((s, i) => (i === 0 ? s.toLocaleLowerCase() : s))
+ .join(' ')}
+ .
+ </span>
+ ) : (
+ !fieldState.error && <span className="h-5" />
+ )}
+ </FormMessage_Shadcn_>
+ </FormItem_Shadcn_>
+ // <FormItemLayout
+ // label=""
+ // layout="vertical"
+ // className="gap-1 "
+ // labelOptional="Should be in this format * * * * *"
+ // >
+ // <FormControl_Shadcn_>
+
+ // </FormControl_Shadcn_>
+ // </FormItemLayout>
+ )
+ }}
+ />
+ </SheetSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/CronJobs.constants.tsx b/apps/studio/components/interfaces/Database/CronJobs/CronJobs.constants.tsx
new file mode 100644
index 00000000000..ec4039916f0
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/CronJobs.constants.tsx
@@ -0,0 +1,41 @@
+import { EdgeFunctions, RESTApi, SqlEditor } from 'icons'
+import { ScrollText } from 'lucide-react'
+
+export const CRONJOB_TYPES = [
+ 'http_request',
+ 'edge_function',
+ 'sql_function',
+ 'sql_snippet',
+] as const
+
+export const CRONJOB_DEFINITIONS = [
+ {
+ value: 'sql_snippet',
+ icon: <SqlEditor strokeWidth={1} />,
+ label: 'SQL Snippet',
+ description: 'Write a SQL snippet to run.',
+ },
+ {
+ value: 'sql_function',
+ icon: <ScrollText strokeWidth={1} />,
+ label: 'Postgres SQL Function',
+ description: 'Choose a Postgres SQL functions to run.',
+ },
+
+ {
+ value: 'http_request',
+ icon: <RESTApi strokeWidth={1} />,
+ label: 'HTTP Request',
+ description: 'Send an HTTP request to any URL.',
+ },
+ {
+ value: 'edge_function',
+ icon: <EdgeFunctions strokeWidth={1} />,
+ label: 'Supabase Edge Function',
+ description: 'Choose a Supabase edge function to run.',
+ },
+]
+
+export type HTTPHeader = { name: string; value: string }
+
+export type HTTPParameter = { name: string; value: string }
diff --git a/apps/studio/components/interfaces/Database/CronJobs/CronJobs.utils.test.ts b/apps/studio/components/interfaces/Database/CronJobs/CronJobs.utils.test.ts
new file mode 100644
index 00000000000..e54f33da4e8
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/CronJobs.utils.test.ts
@@ -0,0 +1,37 @@
+import { it } from 'vitest'
+import { parseCronJobCommand } from './CronJobs.utils'
+
+describe('parseCronJobCommand', () => {
+ it('should return a default object when the command is null', () => {
+ expect(parseCronJobCommand('')).toStrictEqual({ snippet: '', type: 'sql_snippet' })
+ })
+
+ it('should return a default object when the command is random', () => {
+ const command = 'some random text'
+ expect(parseCronJobCommand(command)).toStrictEqual({
+ snippet: 'some random text',
+ type: 'sql_snippet',
+ })
+ })
+
+ it('should return a sql function command when the command is CALL auth.jwt ()', () => {
+ const command = 'CALL auth.jwt ()'
+ expect(parseCronJobCommand(command)).toStrictEqual({
+ type: 'sql_function',
+ schema: 'auth',
+ functionName: 'jwt',
+ })
+ })
+
+ it('should return a edge function config when the command posts to supabase.co', () => {
+ const command = `select net.http_post( url:='https://_.supabase.co/functions/v1/_', headers:=jsonb_build_object(), body:=jsonb_build_object(), timeout_milliseconds:=5000 );`
+ expect(parseCronJobCommand(command)).toStrictEqual({
+ edgeFunctionName: 'https://_.supabase.co/functions/v1/_',
+ method: 'POST',
+ httpHeaders: [],
+ httpParameters: [],
+ timeoutMs: 5000,
+ type: 'edge_function',
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/Database/CronJobs/CronJobs.utils.ts b/apps/studio/components/interfaces/Database/CronJobs/CronJobs.utils.ts
new file mode 100644
index 00000000000..b91865c47d7
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/CronJobs.utils.ts
@@ -0,0 +1,106 @@
+import { CronJobType } from './CreateCronJobSheet'
+import { HTTPHeader, HTTPParameter } from './CronJobs.constants'
+
+export const buildCronQuery = (name: string, schedule: string, command: string) => {
+ return `select cron.schedule('${name}','${schedule}',${command});`
+}
+
+export const buildHttpRequestCommand = (
+ method: 'GET' | 'POST',
+ url: string,
+ headers: HTTPHeader[],
+ body: HTTPParameter[],
+ timeout: number
+) => {
+ return `$$
+ select
+ net.${method === 'GET' ? 'http_get' : 'http_post'}(
+ url:='${url}',
+ headers:=jsonb_build_object(${headers.map((v) => `'${v.name}', '${v.value}'`).join(', ')}),
+ body:=jsonb_build_object(${body.map((v) => `'${v.name}', '${v.value}'`).join(', ')}),
+ timeout_milliseconds:=${timeout}
+ );
+ $$`
+}
+
+export const DEFAULT_CRONJOB_COMMAND = {
+ type: 'sql_snippet',
+ snippet: '',
+} as const
+
+export const parseCronJobCommand = (originalCommand: string): CronJobType => {
+ const command = originalCommand
+ .replaceAll('$$', ' ')
+ .replaceAll(/\n/g, ' ')
+ .replaceAll(/\s+/g, ' ')
+ .trim()
+ if (command.toLocaleLowerCase().startsWith('select net.')) {
+ const matches =
+ command.match(
+ /select net\.([^']+)\(\s*url:='([^']+)',\s*headers:=jsonb_build_object\(([^)]*)\),\s*body:=jsonb_build_object\(([^]*)\s*\),\s*timeout_milliseconds:=(\d+) \)/i
+ ) || []
+
+ // convert the header string to array of objects, clean up the values, trim them of spaces and remove the quotation marks at start and end
+ const headers = (matches[3] || '').split(',').map((s) => s.trim().replace(/^'|'$/g, ''))
+ const headersObjs: { name: string; value: string }[] = []
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i] && headers[i].length > 0) {
+ headersObjs.push({ name: headers[i], value: headers[i + 1] })
+ }
+ }
+
+ // convert the parameter string to array of objects, clean up the values, trim them of spaces and remove the quotation marks at start and end
+ const parameters = (matches[4] || '').split(',').map((s) => s.trim().replace(/^'|'$/g, ''))
+ const parametersObjs: { name: string; value: string }[] = []
+ for (let i = 0; i < parameters.length; i += 2) {
+ if (parameters[i] && parameters[i].length > 0) {
+ parametersObjs.push({ name: parameters[i], value: parameters[i + 1] })
+ }
+ }
+
+ const url = matches[2] || ''
+
+ if (url.includes('.supabase.') && url.includes('/functions/v1/')) {
+ return {
+ type: 'edge_function',
+ method: matches[1] === 'http_get' ? 'GET' : 'POST',
+ edgeFunctionName: url,
+ httpHeaders: headersObjs,
+ httpParameters: parametersObjs,
+ timeoutMs: +matches[5] ?? 1000,
+ }
+ }
+
+ return {
+ type: 'http_request',
+ method: matches[1] === 'http_get' ? 'GET' : 'POST',
+ endpoint: url,
+ httpHeaders: headersObjs,
+ httpParameters: parametersObjs,
+ timeoutMs: +matches[5] ?? 1000,
+ }
+ }
+
+ if (command.toLocaleLowerCase().startsWith('call ')) {
+ const [schemaName, functionName] = command
+ .replace('CALL ', '')
+ .replace('()', '')
+ .trim()
+ .split('.')
+
+ return {
+ type: 'sql_function',
+ schema: schemaName,
+ functionName: functionName,
+ }
+ }
+
+ if (command.length > 0) {
+ return {
+ type: 'sql_snippet',
+ snippet: originalCommand,
+ }
+ }
+
+ return DEFAULT_CRONJOB_COMMAND
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/CronJobsDisabledState.tsx b/apps/studio/components/interfaces/Database/CronJobs/CronJobsDisabledState.tsx
new file mode 100644
index 00000000000..549b05ebd53
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/CronJobsDisabledState.tsx
@@ -0,0 +1,91 @@
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { ExternalLink } from 'lucide-react'
+import Link from 'next/link'
+import { useState } from 'react'
+
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { Button } from 'ui'
+import EnableExtensionModal from '../Extensions/EnableExtensionModal'
+
+export const CronJobsDisabledState = () => {
+ const [showEnableExtensionModal, setShowEnableExtensionModal] = useState(false)
+ const { project } = useProjectContext()
+ const canToggleExtensions = useCheckPermissions(
+ PermissionAction.TENANT_SQL_ADMIN_WRITE,
+ 'extensions'
+ )
+
+ const { data } = useDatabaseExtensionsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const pgCronExtension = (data ?? []).find((ext) => ext.name === 'pg_cron')
+
+ if (!pgCronExtension) return null
+
+ return (
+ <>
+ <div>
+ <div className="w-full px-12 py-12 bg-no-repeat border rounded-md bg-studio border-default">
+ <div className="w-3/5 space-y-8">
+ <div className="space-y-2">
+ <h4 className="text-lg">pg_cron</h4>
+ <p className="text-sm text-foreground-light">
+ Cron jobs in PostgreSQL allow you to schedule and automate tasks such as running SQL
+ queries or maintenance routines at specified intervals. These jobs are managed using
+ cron-like syntax and are executed directly within the PostgreSQL server, making it
+ easy to schedule recurring tasks without needing an external scheduler.
+ </p>
+ </div>
+
+ <div className="flex items-center space-x-2">
+ <Button asChild type="default" icon={<ExternalLink />}>
+ <Link
+ href="https://supabase.com/docs/guides/database/extensions/pg_cron"
+ target="_blank"
+ rel="noreferrer"
+ >
+ About pg_cron
+ </Link>
+ </Button>
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <Button type="primary" onClick={() => setShowEnableExtensionModal(true)}>
+ Enable pg_cron
+ </Button>
+ </Tooltip.Trigger>
+ {!canToggleExtensions && (
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">
+ You need additional permissions to enable pg_cron for this project
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ )}
+ </Tooltip.Root>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <EnableExtensionModal
+ visible={showEnableExtensionModal}
+ extension={pgCronExtension}
+ onCancel={() => setShowEnableExtensionModal(false)}
+ />
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/CronJobsListing.tsx b/apps/studio/components/interfaces/Database/CronJobs/CronJobsListing.tsx
new file mode 100644
index 00000000000..9b63d8ddcd9
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/CronJobsListing.tsx
@@ -0,0 +1,157 @@
+import { ExternalLink } from 'lucide-react'
+import Link from 'next/link'
+import { useEffect, useState } from 'react'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
+import AlertError from 'components/ui/AlertError'
+import { FormHeader } from 'components/ui/Forms/FormHeader'
+import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
+import { CronJob, useCronJobsQuery } from 'data/database-cron-jobs/database-cron-jobs-query'
+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import { Button, Sheet, SheetContent } from 'ui'
+import EnableExtensionModal from '../Extensions/EnableExtensionModal'
+import { CreateCronJobSheet } from './CreateCronJobSheet'
+import { CronJobCard } from './CronJobCard'
+import { CronJobsDisabledState } from './CronJobsDisabledState'
+import DeleteCronJob from './DeleteCronJob'
+
+export const CronJobsListing = () => {
+ const { project } = useProjectContext()
+
+ const [showEnableExtensionModal, setShowEnableExtensionModal] = useState(false)
+ // used for confirmation prompt in the Create Cron Job Sheet
+ const [isClosingCreateCronJobSheet, setIsClosingCreateCronJobSheet] = useState(false)
+ const [createCronJobSheetShown, setCreateCronJobSheetShown] = useState<
+ Pick<CronJob, 'jobname' | 'schedule' | 'active' | 'command'> | undefined
+ >()
+ const [cronJobForDeletion, setCronJobForDeletion] = useState<CronJob | undefined>()
+
+ const {
+ data: cronJobs,
+ error,
+ isLoading,
+ isError,
+ refetch,
+ } = useCronJobsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const { data: extensions, isLoading: isLoadingExtensions } = useDatabaseExtensionsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const pgCronExtension = (extensions ?? []).find((ext) => ext.name === 'pg_cron')
+ const pgCronExtensionInstalled = pgCronExtension?.installed_version
+
+ useEffect(() => {
+ // refetch the cron jobs afte the pgcron extension has been installed
+ if (pgCronExtensionInstalled && isError) {
+ refetch()
+ }
+ }, [isError, pgCronExtensionInstalled, refetch])
+
+ // this avoid showing loading screen when the extension is not installed. Otherwise, we';; have to wait for three
+ // retries (which are sure to fail because the extension is not installed)
+ if (isLoadingExtensions) return <GenericSkeletonLoader />
+ if (!pgCronExtensionInstalled) return <CronJobsDisabledState />
+ if (isLoading) return <GenericSkeletonLoader />
+ if (isError) return <AlertError error={error} subject="Failed to retrieve database cron jobs" />
+
+ return (
+ <>
+ {(cronJobs ?? []).length == 0 ? (
+ <div className="flex h-full w-full items-center justify-center">
+ <ProductEmptyState
+ title="Cron Jobs"
+ ctaButtonLabel="Create a new cron job"
+ onClickCta={() =>
+ setCreateCronJobSheetShown({
+ jobname: '',
+ schedule: '',
+ command: '',
+ active: true,
+ })
+ }
+ >
+ <p className="text-sm text-foreground-light">
+ Cron jobs in PostgreSQL allow you to schedule and automate tasks such as running SQL
+ queries or maintenance routines at specified intervals. These jobs are managed using
+ cron-like syntax and are executed directly within the PostgreSQL server, making it
+ easy to schedule recurring tasks without needing an external scheduler.
+ </p>
+ </ProductEmptyState>
+ </div>
+ ) : (
+ <div className="w-full space-y-4">
+ <FormHeader
+ title="Cron jobs"
+ description="Use cron jobs to schedule and automate tasks such as running SQL queries or maintenance routines at specified intervals."
+ actions={
+ <>
+ <Button asChild type="default" icon={<ExternalLink strokeWidth={1.5} />}>
+ <Link
+ href="https://supabase.com/docs/guides/database/extensions/pg_cron"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Documentation
+ </Link>
+ </Button>
+ <Button
+ type="primary"
+ onClick={() =>
+ setCreateCronJobSheetShown({
+ jobname: '',
+ schedule: '',
+ command: '',
+ active: true,
+ })
+ }
+ >
+ Create a new cron job
+ </Button>
+ </>
+ }
+ />
+ {cronJobs.map((job) => (
+ <CronJobCard
+ job={job}
+ onEditCronJob={(job) => setCreateCronJobSheetShown(job)}
+ onDeleteCronJob={(job) => setCronJobForDeletion(job)}
+ />
+ ))}
+ </div>
+ )}
+ <Sheet
+ open={!!createCronJobSheetShown}
+ onOpenChange={() => setIsClosingCreateCronJobSheet(true)}
+ >
+ <SheetContent size="default" tabIndex={undefined}>
+ <CreateCronJobSheet
+ selectedCronJob={createCronJobSheetShown}
+ onClose={() => {
+ setIsClosingCreateCronJobSheet(false)
+ setCreateCronJobSheetShown(undefined)
+ }}
+ isClosing={isClosingCreateCronJobSheet}
+ setIsClosing={setIsClosingCreateCronJobSheet}
+ />
+ </SheetContent>
+ </Sheet>
+ <DeleteCronJob
+ visible={!!cronJobForDeletion}
+ onClose={() => setCronJobForDeletion(undefined)}
+ cronJob={cronJobForDeletion!}
+ />
+
+ <EnableExtensionModal
+ visible={showEnableExtensionModal}
+ extension={pgCronExtension}
+ onCancel={() => setShowEnableExtensionModal(false)}
+ />
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/DeleteCronJob.tsx b/apps/studio/components/interfaces/Database/CronJobs/DeleteCronJob.tsx
new file mode 100644
index 00000000000..a953b502219
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/DeleteCronJob.tsx
@@ -0,0 +1,60 @@
+import { toast } from 'sonner'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useDatabaseCronJobDeleteMutation } from 'data/database-cron-jobs/database-cron-jobs-delete-mutation'
+import { CronJob } from 'data/database-cron-jobs/database-cron-jobs-query'
+import TextConfirmModal from 'ui-patterns/Dialogs/TextConfirmModal'
+
+interface DeleteCronJobProps {
+ cronJob: CronJob
+ visible: boolean
+ onClose: () => void
+}
+
+const DeleteCronJob = ({ cronJob, visible, onClose }: DeleteCronJobProps) => {
+ const { project } = useProjectContext()
+
+ const { mutate: deleteDatabaseCronJob, isLoading } = useDatabaseCronJobDeleteMutation({
+ onSuccess: () => {
+ toast.success(`Successfully removed cron job ${cronJob.jobname}`)
+ onClose()
+ },
+ })
+
+ async function handleDelete() {
+ if (!project) return console.error('Project is required')
+
+ deleteDatabaseCronJob({
+ jobId: cronJob.jobid,
+ projectRef: project.ref,
+ connectionString: project.connectionString,
+ })
+ }
+
+ if (!cronJob) {
+ return null
+ }
+
+ return (
+ <TextConfirmModal
+ variant="warning"
+ visible={visible}
+ onCancel={() => onClose()}
+ onConfirm={handleDelete}
+ title="Delete this cron job"
+ loading={isLoading}
+ confirmLabel={`Delete cron job ${cronJob.jobname}`}
+ confirmPlaceholder="Type in name of cron job"
+ confirmString={cronJob.jobname ?? 'Unknown'}
+ text={
+ <>
+ <span>This will delete the cron job</span>{' '}
+ <span className="text-bold text-foreground">{cronJob.jobname}</span>
+ </>
+ }
+ alert={{ title: 'You cannot recover this cron job once deleted.' }}
+ />
+ )
+}
+
+export default DeleteCronJob
diff --git a/apps/studio/components/interfaces/Database/CronJobs/EdgeFunctionSection.tsx b/apps/studio/components/interfaces/Database/CronJobs/EdgeFunctionSection.tsx
new file mode 100644
index 00000000000..c4181df1126
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/EdgeFunctionSection.tsx
@@ -0,0 +1,145 @@
+import Link from 'next/link'
+import { UseFormReturn } from 'react-hook-form'
+
+import { useParams } from 'common/hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
+import { useEffect } from 'react'
+import {
+ Button,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormLabel_Shadcn_,
+ FormMessage_Shadcn_,
+ Input,
+ Select_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ SheetSection,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { CreateCronJobForm } from './CreateCronJobSheet'
+
+interface HTTPRequestFieldsProps {
+ form: UseFormReturn<CreateCronJobForm>
+}
+
+const buildFunctionUrl = (slug: string, projectRef: string, restUrl?: string) => {
+ const restUrlTld = restUrl ? new URL(restUrl).hostname.split('.').pop() : 'co'
+ const functionUrl = `https://${projectRef}.supabase.${restUrlTld}/functions/v1/${slug}`
+ return functionUrl
+}
+
+export const EdgeFunctionSection = ({ form }: HTTPRequestFieldsProps) => {
+ const { project: selectedProject } = useProjectContext()
+ const { ref } = useParams()
+ const { data: functions, isSuccess, isLoading } = useEdgeFunctionsQuery({ projectRef: ref })
+
+ const edgeFunctions = functions ?? []
+
+ useEffect(() => {
+ if (isSuccess && edgeFunctions.length > 0) {
+ const fn = edgeFunctions[0]
+ const functionUrl = buildFunctionUrl(
+ fn.slug,
+ selectedProject?.ref || '',
+ selectedProject?.restUrl
+ )
+ form.setValue('values.edgeFunctionName', functionUrl)
+ }
+ }, [isSuccess])
+
+ return (
+ <SheetSection className="flex flex-col gap-3">
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.method"
+ render={({ field }) => (
+ <FormItem_Shadcn_>
+ <FormLabel_Shadcn_>Method</FormLabel_Shadcn_>
+ <Select_Shadcn_ onValueChange={field.onChange} value={field.value}>
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ placeholder="Select a method for the API call" />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectItem_Shadcn_ value="GET">GET</SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="POST">POST</SelectItem_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ {edgeFunctions.length === 0 ? (
+ <div className="space-y-1">
+ <p className="text-sm text-foreground-light">Select which edge function to trigger</p>
+ <div className="px-4 py-4 border rounded bg-surface-300 border-strong flex items-center justify-between space-x-4">
+ <p className="text-sm">No edge functions created yet</p>
+ <Button asChild>
+ <Link href={`/project/${ref}/functions`}>Create an edge function</Link>
+ </Button>
+ </div>
+ </div>
+ ) : edgeFunctions.length > 0 ? (
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.edgeFunctionName"
+ render={({ field }) => {
+ return (
+ <FormItem_Shadcn_>
+ <FormLabel_Shadcn_>Edge Function</FormLabel_Shadcn_>
+ <Select_Shadcn_
+ onValueChange={field.onChange}
+ value={field.value}
+ disabled={isLoading}
+ >
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ placeholder="Select which edge function to trigger" />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ <SelectContent_Shadcn_>
+ {edgeFunctions.map((fn) => {
+ const functionUrl = buildFunctionUrl(
+ fn.slug,
+ selectedProject?.ref || '',
+ selectedProject?.restUrl
+ )
+
+ return (
+ <SelectItem_Shadcn_ key={fn.id} value={functionUrl}>
+ {fn.name}
+ </SelectItem_Shadcn_>
+ )
+ })}
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )
+ }}
+ />
+ ) : null}
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.timeoutMs"
+ render={({ field: { ref, ...rest } }) => (
+ <FormItemLayout label="Timeout" layout="vertical" className="gap-1">
+ <Input
+ {...rest}
+ type="number"
+ placeholder="1000"
+ actions={<p className="text-foreground-light pr-2">ms</p>}
+ />
+ </FormItemLayout>
+ )}
+ />
+ </SheetSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/HttpHeaderFieldsSection.tsx b/apps/studio/components/interfaces/Database/CronJobs/HttpHeaderFieldsSection.tsx
new file mode 100644
index 00000000000..c5c98003897
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/HttpHeaderFieldsSection.tsx
@@ -0,0 +1,145 @@
+import clsx from 'clsx'
+import { ChevronDown, Plus, Trash } from 'lucide-react'
+import { useFieldArray } from 'react-hook-form'
+
+import { useParams } from 'common'
+import { FormSectionLabel } from 'components/ui/Forms/FormSection'
+import { useProjectApiQuery } from 'data/config/project-api-query'
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormMessage_Shadcn_,
+ Input_Shadcn_,
+ SheetSection,
+} from 'ui'
+import { CreateCronJobForm } from './CreateCronJobSheet'
+
+interface HTTPHeaderFieldsSectionProps {
+ fieldName: 'values.httpHeaders' | 'values.httpHeaders'
+}
+
+export const HTTPHeaderFieldsSection = ({ fieldName }: HTTPHeaderFieldsSectionProps) => {
+ // gets the fields through form context
+ const { fields, append, remove } = useFieldArray<CreateCronJobForm>({
+ name: fieldName,
+ })
+
+ const { ref } = useParams()
+ const { data: settings } = useProjectApiQuery({ projectRef: ref })
+ const apiService = settings?.autoApiService
+ const apiKey = apiService?.serviceApiKey ?? '[YOUR API KEY]'
+
+ return (
+ <SheetSection>
+ <FormSectionLabel className="lg:!col-span-4">HTTP Headers</FormSectionLabel>
+ <div className="space-y-2">
+ {fields.map((field, index) => (
+ <div key={field.id} className="flex items-center space-x-2">
+ <FormField_Shadcn_
+ name={`${fieldName}.${index}.name`}
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ size="small"
+ className="w-full"
+ placeholder="Header name"
+ />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+ <FormField_Shadcn_
+ name={`${fieldName}.${index}.value`}
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ value={field.value}
+ size="small"
+ className="w-full"
+ placeholder="Header value"
+ />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <Button
+ type="default"
+ icon={<Trash size={12} />}
+ onClick={() => remove(index)}
+ className="h-[34px] w-[34px]"
+ />
+ </div>
+ ))}
+ <div className="flex items-center">
+ <Button
+ type="default"
+ size="tiny"
+ icon={<Plus />}
+ className={clsx(fieldName === 'values.httpHeaders' && 'rounded-r-none px-3')}
+ onClick={() => append({ name: '', value: '' })}
+ >
+ Add a new header
+ </Button>
+ {fieldName === 'values.httpHeaders' && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="default" className="rounded-l-none px-[4px] py-[5px]">
+ <ChevronDown />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" side="bottom">
+ <DropdownMenuItem
+ key="add-auth-header"
+ onClick={() =>
+ append({
+ name: 'Authorization',
+ value: `Bearer ${apiKey}`,
+ })
+ }
+ >
+ <div className="space-y-1">
+ <p className="block text-foreground">Add auth header with service key</p>
+ <p className="text-foreground-light">
+ Required if your edge function enforces JWT verification
+ </p>
+ </div>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ key="add-source-header"
+ onClick={() =>
+ append({
+ name: 'x-supabase-webhook-source',
+ value: `[Use a secret value]`,
+ })
+ }
+ >
+ <div className="space-y-1">
+ <p className="block text-foreground">Add custom source header</p>
+ <p className="text-foreground-light">
+ Useful to verify that the edge function was triggered from this webhook
+ </p>
+ </div>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ </div>
+ </SheetSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/HttpParameterFieldsSection.tsx b/apps/studio/components/interfaces/Database/CronJobs/HttpParameterFieldsSection.tsx
new file mode 100644
index 00000000000..1f88b719a82
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/HttpParameterFieldsSection.tsx
@@ -0,0 +1,86 @@
+import { Plus, Trash } from 'lucide-react'
+import { useFieldArray } from 'react-hook-form'
+
+import {
+ Button,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormMessage_Shadcn_,
+ Input_Shadcn_,
+ SheetSection,
+} from 'ui'
+import { CreateCronJobForm } from './CreateCronJobSheet'
+
+interface HTTPParameterFieldsSectionProps {
+ fieldName: 'values.httpParameters' | 'values.httpParameters'
+}
+
+export const HTTPParameterFieldsSection = ({ fieldName }: HTTPParameterFieldsSectionProps) => {
+ // gets the fields through form context
+ const { fields, append, remove } = useFieldArray<CreateCronJobForm>({
+ name: fieldName,
+ })
+
+ return (
+ <SheetSection>
+ <span>HTTP Parameters</span>
+ <div className="space-y-2">
+ {fields.map((field, index) => (
+ <div key={field.id} className="flex items-center space-x-2">
+ <FormField_Shadcn_
+ name={`${fieldName}.${index}.name`}
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ size="small"
+ className="w-full"
+ placeholder="Parameter name"
+ />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+ <FormField_Shadcn_
+ name={`${fieldName}.${index}.value`}
+ render={({ field }) => (
+ <FormItem_Shadcn_ className="flex-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ value={field.value}
+ size="small"
+ className="w-full"
+ placeholder="Parameter value"
+ />
+ </FormControl_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <Button
+ type="default"
+ icon={<Trash size={12} />}
+ onClick={() => remove(index)}
+ className="h-[34px] w-[34px]"
+ />
+ </div>
+ ))}
+ <div>
+ <Button
+ type="default"
+ size="tiny"
+ icon={<Plus />}
+ onClick={() => append({ name: '', value: '' })}
+ >
+ Add a new parameter
+ </Button>
+ </div>
+ </div>
+ </SheetSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/HttpRequestSection.tsx b/apps/studio/components/interfaces/Database/CronJobs/HttpRequestSection.tsx
new file mode 100644
index 00000000000..13871ab4d7a
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/HttpRequestSection.tsx
@@ -0,0 +1,75 @@
+import { UseFormReturn } from 'react-hook-form'
+
+import {
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ FormItem_Shadcn_,
+ FormLabel_Shadcn_,
+ FormMessage_Shadcn_,
+ Input,
+ Select_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ SheetSection,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { CreateCronJobForm } from './CreateCronJobSheet'
+
+interface HttpRequestSectionProps {
+ form: UseFormReturn<CreateCronJobForm>
+}
+
+export const HttpRequestSection = ({ form }: HttpRequestSectionProps) => {
+ return (
+ <SheetSection className="flex flex-col gap-3">
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.method"
+ render={({ field }) => (
+ <FormItem_Shadcn_>
+ <FormLabel_Shadcn_>Method</FormLabel_Shadcn_>
+ <Select_Shadcn_ onValueChange={field.onChange} value={field.value}>
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ placeholder="Select a method for the HTTP request" />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectItem_Shadcn_ value="GET">GET</SelectItem_Shadcn_>
+ <SelectItem_Shadcn_ value="POST">POST</SelectItem_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ <FormMessage_Shadcn_ />
+ </FormItem_Shadcn_>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.endpoint"
+ render={({ field: { ref, ...rest } }) => (
+ <FormItemLayout label="Endpoint URL" className="gap-1">
+ <Input {...rest} placeholder="https://api.example.com/endpoint" />
+ </FormItemLayout>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.timeoutMs"
+ render={({ field: { ref, ...rest } }) => (
+ <FormItemLayout label="Timeout" className="gap-1">
+ <Input
+ {...rest}
+ type="number"
+ placeholder="1000"
+ actions={<p className="text-foreground-light pr-2">ms</p>}
+ />
+ </FormItemLayout>
+ )}
+ />
+ </SheetSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/SqlFunctionSection.tsx b/apps/studio/components/interfaces/Database/CronJobs/SqlFunctionSection.tsx
new file mode 100644
index 00000000000..d607b46435d
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/SqlFunctionSection.tsx
@@ -0,0 +1,52 @@
+import { UseFormReturn } from 'react-hook-form'
+
+import FunctionSelector from 'components/ui/FunctionSelector'
+import SchemaSelector from 'components/ui/SchemaSelector'
+import { FormField_Shadcn_, SheetSection } from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { CreateCronJobForm } from './CreateCronJobSheet'
+
+interface SqlFunctionSectionProps {
+ form: UseFormReturn<CreateCronJobForm>
+}
+
+export const SqlFunctionSection = ({ form }: SqlFunctionSectionProps) => {
+ const schema = form.watch('values.schema')
+
+ return (
+ <SheetSection className="flex flex-col gap-3">
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.schema"
+ render={({ field }) => (
+ <FormItemLayout label="Schema" className="gap-1">
+ <SchemaSelector
+ size="small"
+ selectedSchemaName={field.value}
+ onSelectSchema={(name) => {
+ field.onChange(name)
+ // deselect the selected function when the schema is changed
+ form.resetField('values.functionName')
+ }}
+ />
+ </FormItemLayout>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.functionName"
+ render={({ field }) => (
+ <FormItemLayout label="Function name" className="gap-1">
+ <FunctionSelector
+ size="small"
+ schema={schema}
+ value={field.value}
+ onChange={(name) => field.onChange(name)}
+ />
+ </FormItemLayout>
+ )}
+ />
+ </SheetSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/CronJobs/SqlSnippetSection.tsx b/apps/studio/components/interfaces/Database/CronJobs/SqlSnippetSection.tsx
new file mode 100644
index 00000000000..8d3bb465d78
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/CronJobs/SqlSnippetSection.tsx
@@ -0,0 +1,33 @@
+import { UseFormReturn } from 'react-hook-form'
+
+import CodeEditor from 'components/ui/CodeEditor/CodeEditor'
+import { FormField_Shadcn_, SheetSection } from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { CreateCronJobForm } from './CreateCronJobSheet'
+
+interface SqlSnippetSectionProps {
+ form: UseFormReturn<CreateCronJobForm>
+}
+
+export const SqlSnippetSection = ({ form }: SqlSnippetSectionProps) => {
+ return (
+ <SheetSection className="!px-0 !pb-0">
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.snippet"
+ render={({ field }) => (
+ <FormItemLayout label="SQL Snippet" className="[&>div>label]:px-content">
+ <CodeEditor
+ id="create-cron-job-editor"
+ language="pgsql"
+ className="h-72"
+ autofocus={false}
+ value={field.value}
+ onInputChange={field.onChange}
+ />
+ </FormItemLayout>
+ )}
+ />
+ </SheetSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/Extensions/ExtensionCard.tsx b/apps/studio/components/interfaces/Database/Extensions/ExtensionCard.tsx
index adbd8c7a188..75c3dc010c5 100644
--- a/apps/studio/components/interfaces/Database/Extensions/ExtensionCard.tsx
+++ b/apps/studio/components/interfaces/Database/Extensions/ExtensionCard.tsx
@@ -161,6 +161,7 @@ const ExtensionCard = ({ extension }: ExtensionCardProps) => {
visible={isDisableModalOpen}
title="Confirm to disable extension"
confirmLabel="Disable"
+ variant="destructive"
confirmLabelLoading="Disabling"
onCancel={() => setIsDisableModalOpen(false)}
onConfirm={() => onConfirmDisable()}
diff --git a/apps/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx b/apps/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx
index 82594b17652..a8c31f291ef 100644
--- a/apps/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx
+++ b/apps/studio/components/layouts/DatabaseLayout/DatabaseLayout.tsx
@@ -7,6 +7,7 @@ import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-ex
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { withAuth } from 'hooks/misc/withAuth'
+import { useFlag } from 'hooks/ui/useFlag'
import ProjectLayout from '../ProjectLayout/ProjectLayout'
import { generateDatabaseMenu } from './DatabaseMenu.utils'
@@ -29,6 +30,7 @@ const DatabaseProductMenu = () => {
const pgNetExtensionExists = (data ?? []).find((ext) => ext.name === 'pg_net') !== undefined
const pitrEnabled = addons?.selected_addons.find((addon) => addon.type === 'pitr') !== undefined
const columnLevelPrivileges = useIsColumnLevelPrivilegesEnabled()
+ const cronUiEnabled = useFlag('cronUi')
return (
<>
@@ -38,6 +40,7 @@ const DatabaseProductMenu = () => {
pgNetExtensionExists,
pitrEnabled,
columnLevelPrivileges,
+ cronUiEnabled,
})}
/>
</>
diff --git a/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsx b/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsx
index 6ecc8799311..02f7c059f0f 100644
--- a/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsx
+++ b/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsx
@@ -9,10 +9,11 @@ export const generateDatabaseMenu = (
pgNetExtensionExists: boolean
pitrEnabled: boolean
columnLevelPrivileges: boolean
+ cronUiEnabled: boolean
}
): ProductMenuGroup[] => {
const ref = project?.ref ?? 'default'
- const { pgNetExtensionExists, pitrEnabled, columnLevelPrivileges } = flags || {}
+ const { pgNetExtensionExists, pitrEnabled, columnLevelPrivileges, cronUiEnabled } = flags || {}
return [
{
@@ -119,6 +120,16 @@ export const generateDatabaseMenu = (
},
]
: []),
+ ...(!!cronUiEnabled
+ ? [
+ {
+ name: 'Cron Jobs',
+ key: 'cron-jobs',
+ url: `/project/${ref}/database/cron-jobs`,
+ items: [],
+ },
+ ]
+ : []),
],
},
{
diff --git a/apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsx b/apps/studio/components/ui/FunctionSelector.tsx
similarity index 65%
rename from apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsx
rename to apps/studio/components/ui/FunctionSelector.tsx
index 9c17402c1e1..136f2f3b42f 100644
--- a/apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsx
+++ b/apps/studio/components/ui/FunctionSelector.tsx
@@ -1,4 +1,12 @@
+import { uniqBy } from 'lodash'
+import { Check, ChevronsUpDown, Plus } from 'lucide-react'
import { useState } from 'react'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import {
+ DatabaseFunctionsData,
+ useDatabaseFunctionsQuery,
+} from 'data/database-functions/database-functions-query'
import {
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
@@ -9,17 +17,18 @@ import {
CommandInput_Shadcn_,
CommandItem_Shadcn_,
CommandList_Shadcn_,
+ CommandSeparator_Shadcn_,
Command_Shadcn_,
PopoverContent_Shadcn_,
PopoverTrigger_Shadcn_,
Popover_Shadcn_,
ScrollArea,
} from 'ui'
+import { useRouter } from 'next/router'
+import Link from 'next/link'
+import { useParams } from 'common'
-import { convertArgumentTypes } from 'components/interfaces/Database/Functions/Functions.utils'
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import { useDatabaseFunctionsQuery } from 'data/database-functions/database-functions-query'
-import { Check, Code } from 'lucide-react'
+type DatabaseFunction = DatabaseFunctionsData[number]
interface FunctionSelectorProps {
className?: string
@@ -29,6 +38,9 @@ interface FunctionSelectorProps {
value: string
onChange: (value: string) => void
disabled?: boolean
+ // used to filter the functions by a criteria
+ filterFunction?: (func: DatabaseFunction) => boolean
+ noResultsLabel?: React.ReactNode
}
const FunctionSelector = ({
@@ -39,7 +51,11 @@ const FunctionSelector = ({
schema,
value,
onChange,
+ filterFunction = () => true,
+ noResultsLabel = <span>No functions found in this schema.</span>,
}: FunctionSelectorProps) => {
+ const router = useRouter()
+ const { ref } = useParams()
const { project } = useProjectContext()
const [open, setOpen] = useState(false)
@@ -48,14 +64,10 @@ const FunctionSelector = ({
connectionString: project?.connectionString,
})
- const functions = (data ?? [])
+ const filteredFunctions = (data ?? [])
.filter((func) => schema && func.schema === schema)
- .filter((func) => func.return_type === 'json' || func.return_type === 'jsonb')
- .filter((func) => {
- const { value } = convertArgumentTypes(func.argument_types)
- if (value.length !== 1) return false
- return value[0].type === 'json' || value[0].type === 'jsonb'
- })
+ .filter(filterFunction)
+ const functions = uniqBy(filteredFunctions, (func) => func.name)
return (
<div className={className}>
@@ -86,17 +98,23 @@ const FunctionSelector = ({
<PopoverTrigger_Shadcn_ asChild>
<Button
size={size}
+ disabled={!!disabled}
type="default"
className={`w-full [&>span]:w-full ${size === 'small' ? 'py-1.5' : ''}`}
iconRight={
- <Code className="text-foreground-light rotate-90" strokeWidth={2} size={12} />
+ <ChevronsUpDown className="text-foreground-muted" strokeWidth={2} size={14} />
}
- disabled={!!disabled}
>
- <div className="w-full flex gap-1">
- <p className="text-foreground-lighter">function:</p>
- <p className="text-foreground">{value}</p>
- </div>
+ {value ? (
+ <div className="w-full flex gap-1">
+ <p className="text-foreground-lighter">function:</p>
+ <p className="text-foreground">{value}</p>
+ </div>
+ ) : (
+ <div className="w-full flex gap-1">
+ <p className="text-foreground-lighter">Choose a function...</p>
+ </div>
+ )}
</Button>
</PopoverTrigger_Shadcn_>
<PopoverContent_Shadcn_ className="p-0" side="bottom" align="start" sameWidthAsTrigger>
@@ -112,11 +130,7 @@ const FunctionSelector = ({
disabled={true}
className="flex items-center justify-between space-x-2 w-full"
>
- <span>
- No function with a single JSON/B argument
- <br />
- and JSON/B return type found in this schema.
- </span>
+ {noResultsLabel}
</CommandItem_Shadcn_>
)}
{functions?.map((func) => (
@@ -141,6 +155,28 @@ const FunctionSelector = ({
))}
</ScrollArea>
</CommandGroup_Shadcn_>
+ <CommandSeparator_Shadcn_ />
+ <CommandGroup_Shadcn_>
+ <CommandItem_Shadcn_
+ className="cursor-pointer w-full"
+ onSelect={() => {
+ setOpen(false)
+ router.push(`/project/${ref}/database/functions`)
+ }}
+ onClick={() => setOpen(false)}
+ >
+ <Link
+ href={`/project/${ref}/database/functions`}
+ onClick={() => {
+ setOpen(false)
+ }}
+ className="w-full flex items-center gap-2"
+ >
+ <Plus size={14} strokeWidth={1.5} />
+ <p>New function</p>
+ </Link>
+ </CommandItem_Shadcn_>
+ </CommandGroup_Shadcn_>
</CommandList_Shadcn_>
</Command_Shadcn_>
</PopoverContent_Shadcn_>
diff --git a/apps/studio/components/ui/SchemaSelector.tsx b/apps/studio/components/ui/SchemaSelector.tsx
index 7fbc6298aa6..8ab840df5f4 100644
--- a/apps/studio/components/ui/SchemaSelector.tsx
+++ b/apps/studio/components/ui/SchemaSelector.tsx
@@ -100,12 +100,18 @@ const SchemaSelector = ({
<ChevronsUpDown className="text-foreground-muted" strokeWidth={2} size={14} />
}
>
- <div className="w-full flex gap-1">
- <p className="text-foreground-lighter">schema:</p>
- <p className="text-foreground">
- {selectedSchemaName === '*' ? 'All schemas' : selectedSchemaName}
- </p>
- </div>
+ {selectedSchemaName ? (
+ <div className="w-full flex gap-1">
+ <p className="text-foreground-lighter">schema:</p>
+ <p className="text-foreground">
+ {selectedSchemaName === '*' ? 'All schemas' : selectedSchemaName}
+ </p>
+ </div>
+ ) : (
+ <div className="w-full flex gap-1">
+ <p className="text-foreground-lighter">Choose a schema…</p>
+ </div>
+ )}
</Button>
</PopoverTrigger_Shadcn_>
<PopoverContent_Shadcn_ className="p-0" side="bottom" align="start" sameWidthAsTrigger>
diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-create-mutation.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-create-mutation.ts
new file mode 100644
index 00000000000..d05105a295e
--- /dev/null
+++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-create-mutation.ts
@@ -0,0 +1,59 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+import { databaseCronJobsKeys } from './keys'
+
+export type DatabaseCronJobCreateVariables = {
+ projectRef: string
+ connectionString?: string
+ query: string
+}
+
+export async function createDatabaseCronJob({
+ projectRef,
+ connectionString,
+ query,
+}: DatabaseCronJobCreateVariables) {
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: query,
+ queryKey: databaseCronJobsKeys.create(),
+ })
+
+ return result
+}
+
+type DatabaseCronJobCreateData = Awaited<ReturnType<typeof createDatabaseCronJob>>
+
+export const useDatabaseCronJobCreateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<DatabaseCronJobCreateData, ResponseError, DatabaseCronJobCreateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<DatabaseCronJobCreateData, ResponseError, DatabaseCronJobCreateVariables>(
+ (vars) => createDatabaseCronJob(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries(databaseCronJobsKeys.list(projectRef))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to create database cron job: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-delete-mutation.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-delete-mutation.ts
new file mode 100644
index 00000000000..3081d7a1979
--- /dev/null
+++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-delete-mutation.ts
@@ -0,0 +1,59 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+import { databaseCronJobsKeys } from './keys'
+
+export type DatabaseCronJobDeleteVariables = {
+ projectRef: string
+ connectionString?: string
+ jobId: number
+}
+
+export async function deleteDatabaseCronJob({
+ projectRef,
+ connectionString,
+ jobId,
+}: DatabaseCronJobDeleteVariables) {
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: `SELECT cron.unschedule(${jobId});`,
+ queryKey: databaseCronJobsKeys.delete(),
+ })
+
+ return result
+}
+
+type DatabaseCronJobDeleteData = Awaited<ReturnType<typeof deleteDatabaseCronJob>>
+
+export const useDatabaseCronJobDeleteMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<DatabaseCronJobDeleteData, ResponseError, DatabaseCronJobDeleteVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<DatabaseCronJobDeleteData, ResponseError, DatabaseCronJobDeleteVariables>(
+ (vars) => deleteDatabaseCronJob(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries(databaseCronJobsKeys.list(projectRef))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to delete database cron job: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-query.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-query.ts
new file mode 100644
index 00000000000..704c40393e7
--- /dev/null
+++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-query.ts
@@ -0,0 +1,56 @@
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { executeSql } from 'data/sql/execute-sql-query'
+import { ResponseError } from 'types'
+import { databaseCronJobsKeys } from './keys'
+
+export type DatabaseCronJobsVariables = {
+ projectRef?: string
+ connectionString?: string
+}
+
+export type CronJob = {
+ jobid: number
+ schedule: string
+ command: string
+ nodename: string
+ nodeport: number
+ database: string
+ username: string
+ active: boolean
+ jobname: string
+}
+
+const cronJobSqlQuery = `select * from cron.job order by jobid;`
+
+export async function getDatabaseCronJobs({
+ projectRef,
+ connectionString,
+}: DatabaseCronJobsVariables) {
+ if (!projectRef) throw new Error('Project ref is required')
+
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: cronJobSqlQuery,
+ })
+ return result
+}
+
+export type DatabaseCronJobData = CronJob[]
+export type DatabaseCronJobError = ResponseError
+
+export const useCronJobsQuery = <TData = DatabaseCronJobData>(
+ { projectRef, connectionString }: DatabaseCronJobsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<DatabaseCronJobData, DatabaseCronJobError, TData> = {}
+) =>
+ useQuery<DatabaseCronJobData, DatabaseCronJobError, TData>(
+ databaseCronJobsKeys.list(projectRef),
+ () => getDatabaseCronJobs({ projectRef, connectionString }),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ ...options,
+ }
+ )
diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-toggle-mutation.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-toggle-mutation.ts
new file mode 100644
index 00000000000..a1e2112262a
--- /dev/null
+++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-toggle-mutation.ts
@@ -0,0 +1,61 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+import { databaseCronJobsKeys } from './keys'
+
+export type DatabaseCronJobToggleVariables = {
+ projectRef: string
+ connectionString?: string
+ jobId: number
+ active: boolean
+}
+
+export async function toggleDatabaseCronJob({
+ projectRef,
+ connectionString,
+ jobId,
+ active,
+}: DatabaseCronJobToggleVariables) {
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: `select cron.alter_job(job_id := ${jobId}, active := ${active});`,
+ queryKey: databaseCronJobsKeys.alter(),
+ })
+
+ return result
+}
+
+type DatabaseCronJobToggleData = Awaited<ReturnType<typeof toggleDatabaseCronJob>>
+
+export const useDatabaseCronJobToggleMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<DatabaseCronJobToggleData, ResponseError, DatabaseCronJobToggleVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<DatabaseCronJobToggleData, ResponseError, DatabaseCronJobToggleVariables>(
+ (vars) => toggleDatabaseCronJob(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries(databaseCronJobsKeys.list(projectRef))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to toggle database cron job: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/database-cron-jobs/keys.ts b/apps/studio/data/database-cron-jobs/keys.ts
new file mode 100644
index 00000000000..8bd4b049051
--- /dev/null
+++ b/apps/studio/data/database-cron-jobs/keys.ts
@@ -0,0 +1,6 @@
+export const databaseCronJobsKeys = {
+ create: () => ['cron-jobs', 'create'] as const,
+ delete: () => ['cron-jobs', 'delete'] as const,
+ alter: () => ['cronjobs', 'alter'] as const,
+ list: (projectRef: string | undefined) => ['projects', projectRef, 'cron-jobs'] as const,
+}
diff --git a/apps/studio/package.json b/apps/studio/package.json
index 90c7af5eb7d..97f9cac2c07 100644
--- a/apps/studio/package.json
+++ b/apps/studio/package.json
@@ -55,6 +55,7 @@
"common-tags": "^1.8.2",
"config": "*",
"configcat-js": "^7.0.0",
+ "cronstrue": "^2.50.0",
"dayjs": "^1.11.10",
"dnd-core": "^16.0.1",
"file-saver": "^2.0.5",
diff --git a/apps/studio/pages/project/[ref]/database/cron-jobs.tsx b/apps/studio/pages/project/[ref]/database/cron-jobs.tsx
new file mode 100644
index 00000000000..f0fdf1c88a9
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/database/cron-jobs.tsx
@@ -0,0 +1,28 @@
+import { CronJobsListing } from 'components/interfaces/Database/CronJobs/CronJobsListing'
+import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'
+import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
+import type { NextPageWithLayout } from 'types'
+
+const CronJobsPage: NextPageWithLayout = () => {
+ // TODO: Change this to the correct permissions
+ // const canReadFunctions = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'functions')
+ // const isPermissionsLoaded = usePermissionsLoaded()
+
+ // if (isPermissionsLoaded && !canReadFunctions) {
+ // return <NoPermission isFullPage resourceText="manage database cron jobs" />
+ // }
+
+ return (
+ <ScaffoldContainer className="h-full">
+ <ScaffoldSection className="h-full">
+ <div className="col-span-12 h-full pb-8">
+ <CronJobsListing />
+ </div>
+ </ScaffoldSection>
+ </ScaffoldContainer>
+ )
+}
+
+CronJobsPage.getLayout = (page) => <DatabaseLayout title="Database">{page}</DatabaseLayout>
+
+export default CronJobsPage
diff --git a/package-lock.json b/package-lock.json
index 0bbdd849c3e..d9bdda56fe8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1841,6 +1841,7 @@
"common-tags": "^1.8.2",
"config": "*",
"configcat-js": "^7.0.0",
+ "cronstrue": "^2.50.0",
"dayjs": "^1.11.10",
"dnd-core": "^16.0.1",
"file-saver": "^2.0.5",
@@ -19031,6 +19032,14 @@
"optional": true,
"peer": true
},
+ "node_modules/cronstrue": {
+ "version": "2.50.0",
+ "resolved": "https://registry.npmjs.org/cronstrue/-/cronstrue-2.50.0.tgz",
+ "integrity": "sha512-ULYhWIonJzlScCCQrPUG5uMXzXxSixty4djud9SS37DoNxDdkeRocxzHuAo4ImRBUK+mAuU5X9TSwEDccnnuPg==",
+ "bin": {
+ "cronstrue": "bin/cli.js"
+ }
+ },
"node_modules/cross-fetch": {
"version": "3.1.5",
"dev": true,
diff --git a/packages/shared-data/extensions.json b/packages/shared-data/extensions.json
index 53a0cdff892..58201347416 100644
--- a/packages/shared-data/extensions.json
+++ b/packages/shared-data/extensions.json
@@ -229,9 +229,9 @@
"comment": "Job scheduler for PostgreSQL",
"tags": ["Utility"],
"link": "/guides/database/extensions/pg_cron",
- "github_url": null,
- "product": null,
- "product_url": null
+ "github_url": "https://github.com/citusdata/pg_cron",
+ "product": "Supabase Cron Jobs",
+ "product_url": "/project/{ref}/database/cron-jobs"
},
{
"name": "pg_freespacemap",
diff --git a/packages/ui/src/components/radio-group-stacked.tsx b/packages/ui/src/components/radio-group-stacked.tsx
index 20c51211d89..cbc532955b9 100644
--- a/packages/ui/src/components/radio-group-stacked.tsx
+++ b/packages/ui/src/components/radio-group-stacked.tsx
@@ -40,12 +40,13 @@ const RadioGroupStackedItem = React.forwardRef<
className={cn(
'flex flex-col gap-2',
'w-full',
- 'bg-overlay/50',
+ 'bg-overlay/50 disabled:opacity-50',
'border',
'first-of-type:rounded-t-lg last-of-type:rounded-b-lg',
'shadow-sm',
- 'hover:bg-surface-300',
- 'hover:border-foreground-muted',
+ 'enabled:hover:bg-surface-300',
+ 'enabled:hover:border-foreground-muted',
+ 'enabled:cursor-pointer disabled:cursor-not-allowed',
'hover:z-[1] focus-visible:z-[1]',
'data-[state=checked]:z-[1]',
'data-[state=checked]:ring-1 data-[state=checked]:ring-border',
@@ -67,7 +68,6 @@ const RadioGroupStackedItem = React.forwardRef<
'ring-offset-background',
'group-focus:outline-none',
'group-focus-visible:ring-2 group-focus-visible:ring-ring group-focus-visible:ring-offset-2',
- 'group-disabled:cursor-not-allowed group-disabled:opacity-50',
'flex items-center justify-center',
'transition'
)}
@@ -85,8 +85,7 @@ const RadioGroupStackedItem = React.forwardRef<
'-mt-[0.15rem]',
'text-sm transition-colors text-left',
'text-light',
- 'group-hover:text-foreground group-data-[state=checked]:text-foreground',
- props.disabled ? 'cursor-not-allowed' : 'cursor-pointer'
+ 'group-hover:text-foreground group-data-[state=checked]:text-foreground'
)}
>
{label}