Skip to content

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

fix: cron job editing was done by name rather than Job ID (#46486)

Ali Waseem5222f31fe3d1
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.constants.ts b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.constants.ts
index 29fce353d44..45100581cf7 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.constants.ts
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.constants.ts
@@ -103,7 +103,7 @@ const sqlSnippetSchema = z.object({
export const FormSchema = z
.object({
- name: z.string().trim().min(1, 'Please provide a name for your cron job'),
+ name: z.string().trim(),
supportsSeconds: z.boolean(),
schedule: z
.string()
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.tsx
index fd91482fb4c..bd43227d748 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet/CreateCronJobSheet.tsx
@@ -27,7 +27,12 @@ import { Admonition } from 'ui-patterns/admonition'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { CRONJOB_DEFINITIONS } from '../CronJobs.constants'
-import { buildCronQuery, buildHttpRequestCommand, parseCronJobCommand } from '../CronJobs.utils'
+import {
+ buildCronCreateQuery,
+ buildCronUpdateQuery,
+ buildHttpRequestCommand,
+ parseCronJobCommand,
+} from '../CronJobs.utils'
import { EdgeFunctionSection } from '../EdgeFunctionSection'
import { HttpBodyFieldSection } from '../HttpBodyFieldSection'
import { HTTPHeaderFieldsSection } from '../HttpHeaderFieldsSection'
@@ -55,7 +60,8 @@ import { useTrack } from '@/lib/telemetry/track'
interface CreateCronJobSheetProps {
open: boolean
- selectedCronJob?: Pick<CronJob, 'jobname' | 'schedule' | 'active' | 'command'>
+ selectedCronJob?: Pick<CronJob, 'jobname' | 'schedule' | 'active' | 'command'> &
+ Partial<Pick<CronJob, 'jobid'>>
onClose: () => void
}
@@ -93,7 +99,7 @@ export const CreateCronJobSheet = ({ open, selectedCronJob, onClose }: CreateCro
const [isLoadingGetCronJob, setIsLoadingGetCronJob] = useState(false)
const jobId = Number(childId)
- const isEditing = !!selectedCronJob?.jobname
+ const isEditing = selectedCronJob?.jobid !== undefined
const [showEnableExtensionModal, setShowEnableExtensionModal] = useState(false)
const { data = [] } = useDatabaseExtensionsQuery({
@@ -164,6 +170,14 @@ export const CreateCronJobSheet = ({ open, selectedCronJob, onClose }: CreateCro
if (!project) return console.error('Project is required')
if (!isEditing) {
+ if (!name) {
+ return form.setError(
+ 'name',
+ { type: 'manual', message: 'Please provide a name for your cron job' },
+ { shouldFocus: true }
+ )
+ }
+
try {
setIsLoadingGetCronJob(true)
const checkExistingJob = await getDatabaseCronJob({
@@ -191,7 +205,10 @@ export const CreateCronJobSheet = ({ open, selectedCronJob, onClose }: CreateCro
}
}
- const query = buildCronQuery(name, schedule, values.snippet)
+ const query =
+ isEditing && selectedCronJob?.jobid !== undefined
+ ? buildCronUpdateQuery(selectedCronJob.jobid, schedule, values.snippet)
+ : buildCronCreateQuery(name, schedule, values.snippet)
upsertCronJob(
{
@@ -269,7 +286,9 @@ export const CreateCronJobSheet = ({ open, selectedCronJob, onClose }: CreateCro
<div className="flex flex-col h-full" tabIndex={-1}>
<SheetHeader>
<SheetTitle>
- {isEditing ? `Edit ${selectedCronJob.jobname}` : `Create a new cron job`}
+ {isEditing
+ ? `Edit ${selectedCronJob.jobname || 'cron job'}`
+ : `Create a new cron job`}
</SheetTitle>
</SheetHeader>
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts
index 906bb94223b..f79435a6455 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.test.ts
@@ -1,7 +1,28 @@
import { describe, expect, it } from 'vitest'
import { cronPattern, secondsPattern } from './CronJobs.constants'
-import { formatCronJobColumns, parseCronJobCommand } from './CronJobs.utils'
+import {
+ buildCronCreateQuery,
+ buildCronUpdateQuery,
+ formatCronJobColumns,
+ parseCronJobCommand,
+} from './CronJobs.utils'
+
+describe('buildCronQuery', () => {
+ it('uses cron.schedule to create a job by name', () => {
+ expect(buildCronCreateQuery('my-job', '*/5 * * * *', 'select 1')).toBe(
+ "select cron.schedule('my-job', '*/5 * * * *', 'select 1');"
+ )
+ })
+})
+
+describe('buildCronUpdateQuery', () => {
+ it('uses cron.alter_job to update a job by id', () => {
+ expect(buildCronUpdateQuery(42, '*/10 * * * *', 'select 2')).toBe(
+ "select cron.alter_job(job_id := 42, schedule := '*/10 * * * *', command := 'select 2');"
+ )
+ })
+})
describe('parseCronJobCommand', () => {
it('should return a default object when the command is null', () => {
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.tsx
index 522b0bb71d5..ac68d4948f9 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.tsx
@@ -13,10 +13,22 @@ const unescapeSqlLiteral = (value = '', isEscapeString = false) => {
return isEscapeString ? unescaped.replaceAll('\\\\', '\\') : unescaped
}
-export function buildCronQuery(name: string, schedule: string, command: string): SafeSqlFragment {
+export function buildCronCreateQuery(
+ name: string,
+ schedule: string,
+ command: string
+): SafeSqlFragment {
return safeSql`select cron.schedule(${literal(name)}, ${literal(schedule)}, ${literal(command)});`
}
+export function buildCronUpdateQuery(
+ jobId: number,
+ schedule: string,
+ command: string
+): SafeSqlFragment {
+ return safeSql`select cron.alter_job(job_id := ${literal(jobId)}, schedule := ${literal(schedule)}, command := ${literal(command)});`
+}
+
export const buildHttpRequestCommand = (
method: 'GET' | 'POST',
url: string,
diff --git a/e2e/studio/features/cron-jobs.spec.ts b/e2e/studio/features/cron-jobs.spec.ts
index 568c1b4df3c..49838e2c79b 100644
--- a/e2e/studio/features/cron-jobs.spec.ts
+++ b/e2e/studio/features/cron-jobs.spec.ts
@@ -5,6 +5,8 @@ import { releaseFileOnceCleanup, withFileOnceSetup } from '../utils/once-per-fil
import { test, withSetupCleanup } from '../utils/test.js'
import { toUrl } from '../utils/to-url.js'
+type CronJobRow = { jobid: number; schedule: string }
+
/**
* Helper to navigate to the cron overview page
*/
@@ -42,6 +44,32 @@ const deleteJobViaAPI = async (page: Page, ref: string, jobName: string) => {
})
}
+// Creates a cron job with an empty name (as can happen when a job is scheduled directly via SQL)
+// and returns its generated jobid. Such jobs can only be referenced by id, not name.
+const createUnnamedJobViaAPI = async (
+ page: Page,
+ ref: string,
+ command: string
+): Promise<number> => {
+ const response = await page.request.post(toUrl(`/api/platform/pg-meta/${ref}/query`), {
+ failOnStatusCode: true,
+ data: {
+ query: `select cron.schedule('', '*/30 * * * *', $$${command}$$) as jobid;`,
+ },
+ })
+ const rows = (await response.json()) as Array<{ jobid: number }>
+ return rows[0].jobid
+}
+
+const unscheduleJobByIdViaAPI = async (page: Page, ref: string, jobId: number) => {
+ await page.request.post(toUrl(`/api/platform/pg-meta/${ref}/query`), {
+ failOnStatusCode: true,
+ data: {
+ query: `select cron.unschedule(${jobId});`,
+ },
+ })
+}
+
test.describe('Cron Jobs', () => {
test.beforeAll(async () => {
await withFileOnceSetup(import.meta.url, async () => {
@@ -169,6 +197,54 @@ test.describe('Cron Jobs', () => {
})
})
+ // Regression test for FE-3489: editing a cron job that has no name used to create a brand
+ // new job (via cron.schedule) instead of updating the existing one. The edit now goes
+ // through cron.alter_job by jobid, so the original job is updated in place.
+ test('editing an unnamed cron job updates it in place instead of creating a new job', async ({
+ page,
+ ref,
+ }) => {
+ // Unique command so we can reliably find this job (it has no name to search by)
+ const command = `select 'pw_unnamed_edit_job';`
+ let jobId: number | undefined
+
+ await using _ = await withSetupCleanup(
+ async () => {
+ jobId = await createUnnamedJobViaAPI(page, ref, command)
+ },
+ async () => {
+ if (jobId !== undefined) await unscheduleJobByIdViaAPI(page, ref, jobId)
+ }
+ )
+
+ // Unnamed jobs can't be edited from the list context menu, so edit from the detail page
+ await page.goto(toUrl(`/project/${ref}/integrations/cron/jobs/${jobId}`))
+ await page.getByRole('button', { name: 'Edit', exact: true }).click()
+
+ // The sheet falls back to a generic title when the job has no name
+ await expect(
+ page.getByRole('heading', { name: 'Edit cron job' }),
+ 'Edit sheet should open for the unnamed job'
+ ).toBeVisible({ timeout: 30000 })
+
+ // Change the schedule and save
+ await page.getByRole('button', { name: 'Every 5 minutes' }).click()
+ await page.getByRole('button', { name: 'Save cron job' }).click()
+
+ await expect(page.getByText(/Successfully updated cron job/)).toBeVisible({
+ timeout: 10000,
+ })
+
+ // The original job should be updated in place: exactly one job with this command, and its
+ // schedule should reflect the edit. Before the fix a second job would have been created.
+ const jobs = await query<CronJobRow>(
+ `select jobid, schedule from cron.job where command = $$${command}$$;`
+ )
+ expect(jobs, 'Editing should not create a duplicate job').toHaveLength(1)
+ expect(jobs[0].jobid, 'The existing job should be the one updated').toBe(jobId)
+ expect(jobs[0].schedule, 'The schedule should have been updated').toBe('*/5 * * * *')
+ })
+
test('can delete a cron job', async ({ page, ref }) => {
const cronJobName = 'pw_cron_delete_job'
let shouldCleanup = true