Skip to content

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

Chore/cron nl (#30345)

Terry Sutton95219d3e2ab6
diff --git a/apps/studio/components/interfaces/Database/Extensions/ExtensionCard.tsx b/apps/studio/components/interfaces/Database/Extensions/ExtensionCard.tsx
index a393c9eb2d5..f86edb50bc4 100644
--- a/apps/studio/components/interfaces/Database/Extensions/ExtensionCard.tsx
+++ b/apps/studio/components/interfaces/Database/Extensions/ExtensionCard.tsx
@@ -1,5 +1,5 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { Book, Github, Loader2, Settings, AlertCircle } from 'lucide-react'
+import { Book, Github, Loader2, Settings } from 'lucide-react'
import Link from 'next/link'
import { useState } from 'react'
import { toast } from 'sonner'
@@ -9,11 +9,11 @@ import { useDatabaseExtensionDisableMutation } from 'data/database-extensions/da
import { DatabaseExtension } from 'data/database-extensions/database-extensions-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { extensions } from 'shared-data'
-import { Button, cn, Switch, AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_ } from 'ui'
+import { Button, cn, Switch } from 'ui'
+import { Admonition } from 'ui-patterns'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import EnableExtensionModal from './EnableExtensionModal'
import { EXTENSION_DISABLE_WARNINGS } from './Extensions.constants'
-import { Alert } from '@ui/components/shadcn/ui/alert'
interface ExtensionCardProps {
extension: DatabaseExtension
@@ -168,17 +168,14 @@ const ExtensionCard = ({ extension }: ExtensionCardProps) => {
onCancel={() => setIsDisableModalOpen(false)}
onConfirm={() => onConfirmDisable()}
>
- <div className="grid gap-3">
+ <div className="flex flex-col gap-y-3">
<p className="text-sm text-foreground-light">
Are you sure you want to turn OFF the "{extension.name}" extension?
</p>
{EXTENSION_DISABLE_WARNINGS[extension.name] && (
- <Alert_Shadcn_ variant="default" className="mb-2">
- <AlertCircle className="h-4 w-4" />
- <AlertDescription_Shadcn_ className="flex flex-col gap-3">
- {EXTENSION_DISABLE_WARNINGS[extension.name]}
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
+ <Admonition type="warning" className="m-0">
+ {EXTENSION_DISABLE_WARNINGS[extension.name]}
+ </Admonition>
)}
</div>
</ConfirmationModal>
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx
index 32365416b10..5b4e7a5b70f 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CreateCronJobSheet.tsx
@@ -42,6 +42,7 @@ import { HttpRequestSection } from './HttpRequestSection'
import { SqlFunctionSection } from './SqlFunctionSection'
import { SqlSnippetSection } from './SqlSnippetSection'
import EnableExtensionModal from 'components/interfaces/Database/Extensions/EnableExtensionModal'
+import { checkDomainOfScale } from 'recharts/types/util/ChartUtils'
export interface CreateCronJobSheetProps {
selectedCronJob?: Pick<CronJob, 'jobname' | 'schedule' | 'active' | 'command'>
@@ -131,7 +132,7 @@ export const CreateCronJobSheet = ({
resolver: zodResolver(FormSchema),
defaultValues: {
name: selectedCronJob?.jobname || '',
- schedule: selectedCronJob?.schedule || '',
+ schedule: selectedCronJob?.schedule || '* * * * * *',
values: cronJobValues,
},
})
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobScheduleSection.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobScheduleSection.tsx
index 1d71314b921..5adbd02dd10 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobScheduleSection.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobScheduleSection.tsx
@@ -1,108 +1,229 @@
import { toString as CronToString } from 'cronstrue'
+import { motion } from 'framer-motion'
import { useEffect, useState } from 'react'
import { UseFormReturn } from 'react-hook-form'
+import { useDebounce } from 'use-debounce'
+import { useCompletion } from 'ai/react'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useCronTimezoneQuery } from 'data/database-cron-jobs/database-cron-timezone-query'
+import { BASE_PATH } from 'lib/constants'
import {
+ Accordion_Shadcn_,
+ AccordionContent_Shadcn_,
+ AccordionItem_Shadcn_,
+ AccordionTrigger_Shadcn_,
+ Button,
+ cn,
FormControl_Shadcn_,
FormField_Shadcn_,
FormItem_Shadcn_,
FormLabel_Shadcn_,
- FormMessage_Shadcn_,
Input_Shadcn_,
- Select_Shadcn_,
- SelectContent_Shadcn_,
- SelectItem_Shadcn_,
- SelectTrigger_Shadcn_,
- SelectValue_Shadcn_,
SheetSection,
+ Switch,
} from 'ui'
+import { Input } from 'ui-patterns/DataInputs/Input'
import { CreateCronJobForm } from './CreateCronJobSheet'
+import CronSyntaxChart from './CronSyntaxChart'
interface CronJobScheduleSectionProps {
form: UseFormReturn<CreateCronJobForm>
}
-const schedules = [
- { name: 'Every minute', expression: '* * * * *' },
+const presets = [
+ { 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' },
+ { name: 'Every Monday at midnight', expression: '0 0 * * 1' },
+ { name: 'Every night at midnight', expression: '0 0 0 * * *' },
] 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 { project } = useProjectContext()
+ const initialValue = form.getValues('schedule')
+ const { schedule } = form.watch()
const [presetValue, setPresetValue] = useState<string>(initialValue)
+ const [inputValue, setInputValue] = useState(initialValue)
+ const [debouncedValue] = useDebounce(inputValue, 500)
+ const [useNaturalLanguage, setUseNaturalLanguage] = useState(false)
+ const [scheduleString, setScheduleString] = useState('')
- const onChangeSelectValue = (v: string) => {
- setPresetValue(v)
- }
+ const { complete: generateCronSyntax, isLoading: isGeneratingCron } = useCompletion({
+ api: `${BASE_PATH}/api/ai/sql/cron`,
+ onResponse: async (response) => {
+ if (response.ok) {
+ // remove quotes from the cron expression
+ const expression = (await response.text()).trim().replace(/^"|"$/g, '')
+ form.setValue('schedule', expression)
+ setPresetValue(expression)
+ setScheduleString(CronToString(expression))
+ }
+ },
+ onError: (error) => {
+ console.error('Error generating cron:', error)
+ },
+ })
+
+ const { data: timezone } = useCronTimezoneQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ useEffect(() => {
+ if (!useNaturalLanguage || !debouncedValue) return
+ generateCronSyntax(debouncedValue)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [debouncedValue, useNaturalLanguage])
+
+ useEffect(() => {
+ if (!inputValue) return
+
+ // update the cronstrue string when the input value changes
+ try {
+ setScheduleString(CronToString(inputValue))
+ form.setValue('schedule', inputValue)
+ } catch {}
+ }, [form, inputValue])
useEffect(() => {
- if (presetValue !== 'custom') {
- form.setValue('schedule', presetValue)
+ if (!useNaturalLanguage) {
+ setPresetValue(schedule)
+ setScheduleString(CronToString(schedule))
}
- }, [presetValue, form])
+ }, [schedule])
return (
<SheetSection>
<FormField_Shadcn_
control={form.control}
name="schedule"
- render={({ field, fieldState }) => {
- let scheduleString = ''
- try {
- scheduleString = CronToString(field.value)
- } catch {}
-
+ render={({ field }) => {
return (
<FormItem_Shadcn_ className="flex flex-col gap-1">
<FormLabel_Shadcn_>Schedule</FormLabel_Shadcn_>
+ <FormLabel_Shadcn_ className="text-foreground-lighter">
+ {useNaturalLanguage ? 'Describe your schedule in words' : 'Enter a cron expression'}
+ </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 className="flex flex-col gap-y-2">
+ {useNaturalLanguage ? (
+ <Input
+ value={inputValue}
+ placeholder="E.g. every 5 minutes"
+ className={cn(!useNaturalLanguage && 'hidden')}
+ onChange={(e) => setInputValue(e.target.value)}
+ />
+ ) : (
+ <Input_Shadcn_
+ {...field}
+ autoComplete="off"
+ placeholder="* * * * *"
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault()
+ }
+ }}
+ />
+ )}
+
+ <div className="flex items-center gap-2 mt-2">
+ <Switch
+ checked={useNaturalLanguage}
+ onCheckedChange={() => {
+ setUseNaturalLanguage(!useNaturalLanguage)
+ setInputValue('')
+ setPresetValue('')
+ setScheduleString('')
+ }}
+ />
+ <p className="text-sm text-foreground-light">Use natural language</p>
+ </div>
+
+ <div className="mt-2">
+ <ul className="flex gap-2 flex-wrap mt-2">
+ {presets.map((preset) => (
+ <li key={preset.name}>
+ <Button
+ type="outline"
+ onClick={() => {
+ setUseNaturalLanguage(false)
+ form.setValue('schedule', preset.expression)
+ setPresetValue(preset.expression)
+ }}
+ >
+ {preset.name}
+ </Button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ <Accordion_Shadcn_ type="single" collapsible className="mt-2 pb-2">
+ <AccordionItem_Shadcn_ value="item-1" className="border-none">
+ <AccordionTrigger_Shadcn_ className="text-xs text-foreground-light font-normal gap-2 justify-start py-1 ">
+ View syntax chart
+ </AccordionTrigger_Shadcn_>
+ <AccordionContent_Shadcn_ asChild className="!pb-0">
+ <CronSyntaxChart />
+ </AccordionContent_Shadcn_>
+ </AccordionItem_Shadcn_>
+ </Accordion_Shadcn_>
</div>
</FormControl_Shadcn_>
- <FormMessage_Shadcn_ className="mt-1">
+
+ <div className="bg-surface-100 p-4 rounded grid gap-y-4 border">
+ <h4 className="text-sm text-foreground">
+ Schedule {timezone ? `(${timezone})` : ''}
+ </h4>
{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
+ className={cn(
+ 'text-xl font-mono',
+ isGeneratingCron ? 'animate-pulse text-foreground-lighter' : 'text-foreground'
+ )}
+ >
+ {isGeneratingCron ? <CronSyntaxLoader /> : presetValue || '* * * * * *'}
</span>
) : (
- !fieldState.error && <span className="h-5" />
+ <span className="text-xl font-mono text-foreground-lighter">
+ {isGeneratingCron ? <CronSyntaxLoader /> : presetValue || '* * * * * *'}
+ </span>
)}
- </FormMessage_Shadcn_>
+ {!inputValue && !isGeneratingCron && !scheduleString ? (
+ <span className="text-sm text-foreground-light">
+ Describe your schedule above
+ </span>
+ ) : scheduleString ? (
+ <span className="text-sm text-foreground-light flex items-center gap-2">
+ The cron will be run {/* lowercase the first letter */}
+ {isGeneratingCron ? (
+ <span className="inline-flex items-center">
+ {[0, 1, 2].map((i) => (
+ <motion.span
+ key={i}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ transition={{
+ duration: 0.5,
+ repeat: Infinity,
+ repeatType: 'reverse',
+ delay: i * 0.2,
+ }}
+ >
+ .
+ </motion.span>
+ ))}
+ </span>
+ ) : (
+ scheduleString
+ .split(' ')
+ .map((s, i) => (i === 0 ? s.toLocaleLowerCase() : s))
+ .join(' ') + '.'
+ )}
+ </span>
+ ) : null}
+ </div>
</FormItem_Shadcn_>
)
}}
@@ -110,3 +231,25 @@ export const CronJobScheduleSection = ({ form }: CronJobScheduleSectionProps) =>
</SheetSection>
)
}
+
+const CronSyntaxLoader = () => {
+ return (
+ <div className="flex gap-2">
+ {['*', '*', '*', '*', '*', '*'].map((char, i) => (
+ <motion.span
+ key={i}
+ initial={{ opacity: 0.3 }}
+ animate={{ opacity: 1 }}
+ transition={{
+ duration: 0.6,
+ repeat: Infinity,
+ repeatType: 'reverse',
+ delay: i * 0.15,
+ }}
+ >
+ {char}
+ </motion.span>
+ ))}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsListing.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsListing.tsx
index edfe0766c69..2ae618a7a8c 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsListing.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsListing.tsx
@@ -1,24 +1,17 @@
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-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 'components/interfaces/Database/Extensions/EnableExtensionModal'
-import { DocsButton } from 'components/ui/DocsButton'
-import { CreateCronJobSheet } from './CreateCronJobSheet'
import { CronJobCard } from './CronJobCard'
-import { CronJobsDisabledState } from './CronJobsDisabledState'
import DeleteCronJob from './DeleteCronJob'
+import { Sheet, SheetContent } from 'ui'
+import { CreateCronJobSheet } from 'components/interfaces/Integrations/CronJobs/CreateCronJobSheet'
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<
@@ -26,64 +19,16 @@ export const CronJobsListing = () => {
>()
const [cronJobForDeletion, setCronJobForDeletion] = useState<CronJob | undefined>()
- const {
- data: cronJobs,
- error,
- isLoading,
- isError,
- refetch,
- } = useCronJobsQuery({
+ const { data: cronJobs, isLoading } = 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'll 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 (
<>
<div className="w-full space-y-4">
- <FormHeader
- title="Cron jobs"
- description="Schedule and automate tasks like running queries or maintenance routines at specified intervals"
- actions={
- <>
- <DocsButton href="https://supabase.com/docs/guides/database/extensions/pg_cron" />
- <Button
- type="primary"
- onClick={() =>
- setCreateCronJobSheetShown({
- jobname: '',
- schedule: '',
- command: '',
- active: true,
- })
- }
- >
- Create a new cron job
- </Button>
- </>
- }
- />
{(cronJobs ?? []).length == 0 ? (
<div className="grid text-center h-full w-full items-center justify-center border border-border rounded-md p-4 border-dashed">
<p className="text-sm text-foreground">No cron jobs created yet</p>
@@ -93,7 +38,7 @@ export const CronJobsListing = () => {
</div>
) : (
<div className="w-full space-y-4">
- {cronJobs.map((job) => (
+ {(cronJobs ?? []).map((job) => (
<CronJobCard
job={job}
onEditCronJob={(job) => setCreateCronJobSheetShown(job)}
@@ -104,6 +49,12 @@ export const CronJobsListing = () => {
)}
</div>
+ <DeleteCronJob
+ visible={!!cronJobForDeletion}
+ onClose={() => setCronJobForDeletion(undefined)}
+ cronJob={cronJobForDeletion!}
+ />
+
<Sheet
open={!!createCronJobSheetShown}
onOpenChange={() => setIsClosingCreateCronJobSheet(true)}
@@ -120,16 +71,6 @@ export const CronJobsListing = () => {
/>
</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/Integrations/CronJobs/CronSyntaxChart.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronSyntaxChart.tsx
new file mode 100644
index 00000000000..6bd57df71d3
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronSyntaxChart.tsx
@@ -0,0 +1,18 @@
+export default function CronSyntaxChart() {
+ return (
+ <div>
+ <pre className="text-xs font-mono text-foreground-light">
+ {/* prettier-ignore */}
+ {`
+┌───────────── second (0 - 59)
+│ ┌───────────── minute (0 - 59)
+│ │ ┌───────────── hour (0 - 23)
+│ │ │ ┌───────────── day of month (1 - 31)
+│ │ │ │ ┌───────────── month (1 - 12)
+│ │ │ │ │ ┌───────────── day of week (0 - 7)
+│ │ │ │ │ │
+* * * * * * `}
+ </pre>
+ </div>
+ )
+}
diff --git a/apps/studio/data/database-cron-jobs/database-cron-timezone-query.ts b/apps/studio/data/database-cron-jobs/database-cron-timezone-query.ts
new file mode 100644
index 00000000000..ec9423fcba5
--- /dev/null
+++ b/apps/studio/data/database-cron-jobs/database-cron-timezone-query.ts
@@ -0,0 +1,38 @@
+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 async function getDatabaseCronTimezone({
+ projectRef,
+ connectionString,
+}: DatabaseCronJobsVariables) {
+ if (!projectRef) throw new Error('Project ref is required')
+
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: `select setting from pg_settings where name = 'cron.timezone';`,
+ })
+ return result[0].setting
+}
+
+export type DatabaseCronJobError = ResponseError
+
+export const useCronTimezoneQuery = <TData = string>(
+ { projectRef, connectionString }: DatabaseCronJobsVariables,
+ { enabled = true, ...options }: UseQueryOptions<string, DatabaseCronJobError, TData> = {}
+) =>
+ useQuery<string, DatabaseCronJobError, TData>(
+ databaseCronJobsKeys.timezone(projectRef),
+ () => getDatabaseCronTimezone({ projectRef, connectionString }),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ ...options,
+ }
+ )
diff --git a/apps/studio/data/database-cron-jobs/keys.ts b/apps/studio/data/database-cron-jobs/keys.ts
index 8bd4b049051..5df1b7ec631 100644
--- a/apps/studio/data/database-cron-jobs/keys.ts
+++ b/apps/studio/data/database-cron-jobs/keys.ts
@@ -3,4 +3,5 @@ export const databaseCronJobsKeys = {
delete: () => ['cron-jobs', 'delete'] as const,
alter: () => ['cronjobs', 'alter'] as const,
list: (projectRef: string | undefined) => ['projects', projectRef, 'cron-jobs'] as const,
+ timezone: (projectRef: string | undefined) => ['database-cron-timezone', projectRef] as const,
}
diff --git a/apps/studio/middleware.ts b/apps/studio/middleware.ts
index 935169b1b42..717606e7347 100644
--- a/apps/studio/middleware.ts
+++ b/apps/studio/middleware.ts
@@ -11,6 +11,7 @@ const HOSTED_SUPPORTED_API_URLS = [
'/ai/sql/generate-v2',
'/ai/sql/title',
'/ai/sql/debug',
+ '/ai/sql/cron',
'/get-ip-address',
]
diff --git a/apps/studio/pages/api/ai/sql/cron.ts b/apps/studio/pages/api/ai/sql/cron.ts
new file mode 100644
index 00000000000..23d807d399e
--- /dev/null
+++ b/apps/studio/pages/api/ai/sql/cron.ts
@@ -0,0 +1,59 @@
+import { ContextLengthError } from 'ai-commands'
+import { generateCron } from 'ai-commands/edge'
+import apiWrapper from 'lib/api/apiWrapper'
+import { NextApiRequest, NextApiResponse } from 'next'
+import OpenAI from 'openai'
+
+const openAiKey = process.env.OPENAI_API_KEY
+const openai = new OpenAI({ apiKey: openAiKey })
+
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!openAiKey) {
+ return res.status(500).json({
+ error: 'No OPENAI_API_KEY set. Create this environment variable to use AI features.',
+ })
+ }
+
+ const { method } = req
+
+ switch (method) {
+ case 'POST':
+ return handlePost(req, res)
+ default:
+ res.setHeader('Allow', ['POST'])
+ res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
+ }
+}
+
+export async function handlePost(req: NextApiRequest, res: NextApiResponse) {
+ const {
+ body: { prompt },
+ } = req
+
+ try {
+ const result = await generateCron(openai, prompt)
+
+ return res.json(result)
+ } catch (error) {
+ if (error instanceof Error) {
+ console.error(`AI cron generation failed: ${error.message}`)
+
+ if (error instanceof ContextLengthError) {
+ return res.status(400).json({
+ error:
+ 'Your cron prompt is too large for Supabase AI to ingest. Try splitting it into smaller prompts.',
+ })
+ }
+ } else {
+ console.log(`Unknown error: ${error}`)
+ }
+
+ return res.status(500).json({
+ error: 'There was an unknown error generating the cron syntax. Please try again.',
+ })
+ }
+}
+
+const wrapper = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+
+export default wrapper
diff --git a/apps/studio/pages/project/[ref]/integrations/cron-jobs.tsx b/apps/studio/pages/project/[ref]/integrations/cron-jobs.tsx
index 329da3177e4..1a59917e814 100644
--- a/apps/studio/pages/project/[ref]/integrations/cron-jobs.tsx
+++ b/apps/studio/pages/project/[ref]/integrations/cron-jobs.tsx
@@ -1,24 +1,101 @@
import { CronJobsListing } from 'components/interfaces/Integrations/CronJobs/CronJobsListing'
import ProjectIntegrationsLayout from 'components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
+import { DocsButton } from 'components/ui/DocsButton'
+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 { useEffect, useState } from 'react'
import type { NextPageWithLayout } from 'types'
+import { Button } from 'ui'
+import { CronJobsDisabledState } from '../../../../components/interfaces/Integrations/CronJobs/CronJobsDisabledState'
+
+import { CreateCronJobSheet } from 'components/interfaces/Integrations/CronJobs/CreateCronJobSheet'
+import { Sheet, SheetContent } from 'ui'
const CronJobsPage: NextPageWithLayout = () => {
- // TODO: Change this to the correct permissions
- // const canReadFunctions = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'functions')
- // const isPermissionsLoaded = usePermissionsLoaded()
+ const { project } = useProjectContext()
+ const [isClosingCreateCronJobSheet, setIsClosingCreateCronJobSheet] = useState(false)
+ const [createCronJobSheetShown, setCreateCronJobSheetShown] = useState<
+ Pick<CronJob, 'jobname' | 'schedule' | 'active' | 'command'> | undefined
+ >()
+
+ const { isError, refetch } = useCronJobsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const { data: extensions, isLoading: isLoadingExtensions } = useDatabaseExtensionsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
- // if (isPermissionsLoaded && !canReadFunctions) {
- // return <NoPermission isFullPage resourceText="manage database cron jobs" />
- // }
+ const pgCronExtension = (extensions ?? []).find((ext) => ext.name === 'pg_cron')
+ const pgCronExtensionInstalled = pgCronExtension?.installed_version
+
+ useEffect(() => {
+ // refetch the cron jobs after the pgcron extension has been installed
+ if (pgCronExtensionInstalled && isError) {
+ refetch()
+ }
+ }, [isError, pgCronExtensionInstalled, refetch])
return (
<ScaffoldContainer className="h-full">
<ScaffoldSection className="h-full">
<div className="col-span-12 h-full pb-8">
- <CronJobsListing />
+ {pgCronExtensionInstalled && (
+ <FormHeader
+ title="Cron jobs"
+ description="Schedule and automate tasks like running queries or maintenance routines at specified intervals"
+ actions={
+ <>
+ <DocsButton href="https://supabase.com/docs/guides/database/extensions/pg_cron" />
+ <Button
+ type="primary"
+ onClick={() =>
+ setCreateCronJobSheetShown({
+ jobname: '',
+ schedule: '',
+ command: '',
+ active: true,
+ })
+ }
+ >
+ Create a new cron job
+ </Button>
+ </>
+ }
+ />
+ )}
+ {isLoadingExtensions ? (
+ <GenericSkeletonLoader />
+ ) : !pgCronExtensionInstalled ? (
+ <CronJobsDisabledState />
+ ) : (
+ <CronJobsListing />
+ )}
</div>
</ScaffoldSection>
+
+ <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>
</ScaffoldContainer>
)
}
diff --git a/apps/studio/pages/project/[ref]/integrations/wrappers/index.tsx b/apps/studio/pages/project/[ref]/integrations/wrappers/index.tsx
index aae646b283d..fa21318f6c4 100644
--- a/apps/studio/pages/project/[ref]/integrations/wrappers/index.tsx
+++ b/apps/studio/pages/project/[ref]/integrations/wrappers/index.tsx
@@ -1,5 +1,4 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { ExternalLink } from 'lucide-react'
import { Wrappers } from 'components/interfaces/Database'
import WrappersDropdown from 'components/interfaces/Database/Wrappers/WrappersDropdown'
@@ -11,15 +10,14 @@ import {
ScaffoldSectionContent,
ScaffoldSectionDetail,
} from 'components/layouts/Scaffold'
+import { DocsButton } from 'components/ui/DocsButton'
import { FormHeader } from 'components/ui/Forms/FormHeader'
import NoPermission from 'components/ui/NoPermission'
import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
import { useFDWsQuery } from 'data/fdw/fdws-query'
import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'
import type { NextPageWithLayout } from 'types'
-import { Button } from 'ui'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
-import { DocsButton } from 'components/ui/DocsButton'
const DatabaseWrappers: NextPageWithLayout = () => {
const { project } = useProjectContext()
diff --git a/packages/ai-commands/edge.ts b/packages/ai-commands/edge.ts
index d73e04b769f..51b414c885b 100644
--- a/packages/ai-commands/edge.ts
+++ b/packages/ai-commands/edge.ts
@@ -3,3 +3,4 @@ export * from './src/errors'
export * from './src/docs'
export * from './src/sql/rls'
export * from './src/sql/chat'
+export * from './src/sql/cron'
diff --git a/packages/ai-commands/src/sql/cron.ts b/packages/ai-commands/src/sql/cron.ts
new file mode 100644
index 00000000000..c9f0ce5fdb1
--- /dev/null
+++ b/packages/ai-commands/src/sql/cron.ts
@@ -0,0 +1,97 @@
+import type OpenAI from 'openai'
+import { ContextLengthError } from '../errors'
+import { jsonrepair } from 'jsonrepair'
+import { codeBlock } from 'common-tags'
+
+// Responds to a natural language request for cron syntax.
+export async function generateCron(openai: OpenAI, prompt: string) {
+ const initMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
+ {
+ role: 'system',
+ content: codeBlock`
+ You are a cron syntax expert. Your purpose is to convert natural language time descriptions into valid cron expressions for pg_cron.
+
+ Rules for responses:
+ - Output cron expressions in the 6-field format supported by pg_cron (seconds minute hour day month weekday)
+ - The seconds field is optional - if not specified, it defaults to 0
+ - Provide a brief explanation of what the cron expression does
+ - Format output as markdown with the cron expression in a code block
+ - If the request is unclear or impossible, ask for clarification
+ - If the request isn't related to cron scheduling, explain that you can only help with cron expressions
+
+ Example input: "Every Monday at 3am"
+ Example output:
+ This cron expression runs every Monday at 3:00:00 AM:
+ \`\`\`
+ 0 0 3 * * 1
+ \`\`\`
+
+ Common patterns to remember:
+ - * means "every" for that field
+ - */n means "every n intervals"
+ - n means "exactly at n"
+ - n,m means "at n and m"
+ - n-m means "every value from n to m"
+
+ Field order: seconds (0-59), minute (0-59), hour (0-23), day (1-31), month (1-12), weekday (0-6, Sunday=0)
+
+ Here is the user's prompt:
+ ${prompt}
+ `,
+ },
+ ]
+
+ const completionFunction = {
+ name: 'generateCronSyntax',
+ description: 'Generates a cron expression for a given natural language description.',
+ parameters: {
+ type: 'object',
+ properties: {
+ cron_expression: {
+ type: 'string',
+ description: 'The generated cron expression.',
+ },
+ },
+ required: ['cron_expression'],
+ },
+ }
+
+ try {
+ const response = await openai.chat.completions.create({
+ model: 'gpt-4o-mini-2024-07-18',
+ messages: initMessages,
+ max_tokens: 1024,
+ temperature: 0,
+ stream: false,
+ tool_choice: {
+ type: 'function',
+ function: {
+ name: completionFunction.name,
+ },
+ },
+ tools: [
+ {
+ type: 'function',
+ function: completionFunction,
+ },
+ ],
+ })
+
+ // Parse the JSON string in arguments using jsonrepair
+ const functionArgs = response?.choices?.[0]?.message?.tool_calls?.[0]?.function?.arguments
+ if (!functionArgs) {
+ throw new Error('No cron expression generated')
+ }
+
+ // Use jsonrepair before parsing
+ const repairedJsonString = jsonrepair(functionArgs)
+ const args = JSON.parse(repairedJsonString)
+
+ return args.cron_expression
+ } catch (error) {
+ if (error instanceof Error && 'code' in error && error.code === 'context_length_exceeded') {
+ throw new ContextLengthError()
+ }
+ throw error
+ }
+}