Skip to content

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

feat: Cron tab for previous runs (#30690)

Ivan Vasilov492c81c9c898
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobCard.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobCard.tsx
index fd09c29cd3c..d8bbd50102b 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobCard.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobCard.tsx
@@ -27,10 +27,6 @@ interface CronJobCardProps {
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()
@@ -81,9 +77,7 @@ export const CronJobCard = ({ job, onEditCronJob, onDeleteCronJob }: CronJobCard
Edit cron job
</DropdownMenuItem>
<DropdownMenuItem asChild>
- <Link
- href={`/project/${ref}/sql/new?content=${encodeURIComponent(generateJobDetailsSQL(job.jobid))}`}
- >
+ <Link href={`/project/${ref}/integrations/cron-jobs/cron-jobs/${job.jobname}`}>
View previous runs
</Link>
</DropdownMenuItem>
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.constants.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.constants.tsx
index ec4039916f0..470a2c97d4a 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.constants.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.constants.tsx
@@ -18,8 +18,8 @@ export const CRONJOB_DEFINITIONS = [
{
value: 'sql_function',
icon: <ScrollText strokeWidth={1} />,
- label: 'Postgres SQL Function',
- description: 'Choose a Postgres SQL functions to run.',
+ label: 'Database function',
+ description: 'Choose a database function to run.',
},
{
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts
index af9f02fa528..8ad110fa62c 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.utils.ts
@@ -111,7 +111,36 @@ export const parseCronJobCommand = (originalCommand: string): CronJobType => {
return DEFAULT_CRONJOB_COMMAND
}
+export function calculateDuration(start: string, end: string): string {
+ const startTime = new Date(start).getTime()
+ const endTime = new Date(end).getTime()
+ const duration = endTime - startTime
+ return isNaN(duration) ? 'Invalid Date' : `${duration} ms`
+}
+
+export function formatDate(dateString: string): string {
+ const date = new Date(dateString)
+ if (isNaN(date.getTime())) {
+ return 'Invalid Date'
+ }
+ const options: Intl.DateTimeFormatOptions = {
+ year: 'numeric',
+ month: 'short', // Use 'long' for full month name
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ hour12: false, // Use 12-hour format if preferred
+ timeZoneName: 'short', // Optional: to include timezone
+ }
+ return date.toLocaleString(undefined, options)
+}
+
// detect seconds like "10 seconds" or normal cron syntax like "*/5 * * * *"
export const secondsPattern = /^\d+\s+seconds$/
export const cronPattern =
/^(\*|(\d+|\*\/\d+)|\d+\/\d+|\d+-\d+|\d+(,\d+)*)(\s+(\*|(\d+|\*\/\d+)|\d+\/\d+|\d+-\d+|\d+(,\d+)*)){4}$/
+
+export function isSecondsFormat(schedule: string): boolean {
+ return secondsPattern.test(schedule.trim())
+}
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsEmptyState.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsEmptyState.tsx
new file mode 100644
index 00000000000..9abe797ab7d
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsEmptyState.tsx
@@ -0,0 +1,14 @@
+export default function CronJobsEmptyState({ page }: { page: string }) {
+ return (
+ <div className=" text-center h-full w-full items-center justify-center rounded-md px-4 py-12 ">
+ <p className="text-sm text-foreground">
+ {page === 'jobs' ? 'No cron jobs created yet' : 'No runs for this cron job yet'}
+ </p>
+ <p className="text-sm text-foreground-lighter">
+ {page === 'jobs'
+ ? 'Create one by clicking "Create a new cron job"'
+ : 'Check the schedule of your cron jobs to see when they run'}
+ </p>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsTab.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsTab.tsx
index 8f89f3668b6..8136e14a377 100644
--- a/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsTab.tsx
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/CronJobsTab.tsx
@@ -26,7 +26,6 @@ export const CronjobsTab = () => {
projectRef: project?.ref,
connectionString: project?.connectionString,
})
-
if (isLoading)
return (
<div className="p-10">
@@ -95,9 +94,14 @@ export const CronjobsTab = () => {
Your search for "{searchQuery}" did not return any results
</p>
</div>
+ ) : isLoading ? (
+ <div className="p-10">
+ <GenericSkeletonLoader />
+ </div>
) : (
filteredCronJobs.map((job) => (
<CronJobCard
+ key={job.jobid}
job={job}
onEditCronJob={(job) => setCreateCronJobSheetShown(job)}
onDeleteCronJob={(job) => setCronJobForDeletion(job)}
diff --git a/apps/studio/components/interfaces/Integrations/CronJobs/PreviousRunsTab.tsx b/apps/studio/components/interfaces/Integrations/CronJobs/PreviousRunsTab.tsx
new file mode 100644
index 00000000000..1beebad7e4d
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/CronJobs/PreviousRunsTab.tsx
@@ -0,0 +1,283 @@
+import { toString as CronToString } from 'cronstrue'
+import { List } from 'lucide-react'
+import Link from 'next/link'
+import { UIEvent, useCallback, useMemo } from 'react'
+import DataGrid, { Column, Row } from 'react-data-grid'
+
+import { useParams } from 'common'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useCronJobsQuery } from 'data/database-cron-jobs/database-cron-jobs-query'
+import {
+ CronJobRun,
+ useCronJobRunsInfiniteQuery,
+} from 'data/database-cron-jobs/database-cron-jobs-runs-infinite-query'
+import {
+ Badge,
+ Button,
+ cn,
+ LoadingLine,
+ SimpleCodeBlock,
+ Tooltip_Shadcn_,
+ TooltipContent_Shadcn_,
+ TooltipTrigger_Shadcn_,
+} from 'ui'
+import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
+import { calculateDuration, formatDate, isSecondsFormat } from './CronJobs.utils'
+import CronJobsEmptyState from './CronJobsEmptyState'
+
+const cronJobColumns = [
+ {
+ id: 'runid',
+ name: 'RunID',
+ minWidth: 60,
+ value: (row: CronJobRun) => (
+ <div className="flex items-center gap-1.5">
+ <h3 className="text-xs">{row.runid}</h3>
+ </div>
+ ),
+ },
+ {
+ id: 'message',
+ name: 'Message',
+ minWidth: 200,
+ value: (row: CronJobRun) => (
+ <div className="flex items-center gap-1.5">
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ asChild>
+ <span className="text-xs cursor-pointer truncate max-w-[300px]">
+ {row.return_message}
+ </span>
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_ side="bottom" align="center" className="max-w-[300px] text-wrap">
+ <SimpleCodeBlock
+ showCopy={true}
+ className="sql"
+ parentClassName="!p-0 [&>div>span]:text-xs"
+ >
+ {row.return_message}
+ </SimpleCodeBlock>
+ </TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
+ </div>
+ ),
+ },
+
+ {
+ id: 'status',
+ name: 'Status',
+ minWidth: 75,
+ value: (row: CronJobRun) => (
+ <Badge variant={row.status === 'succeeded' ? 'success' : 'warning'}>{row.status}</Badge>
+ ),
+ },
+ {
+ id: 'start_time',
+ name: 'Start Time',
+ minWidth: 120,
+ value: (row: CronJobRun) => <div className="text-xs">{formatDate(row.start_time)}</div>,
+ },
+ {
+ id: 'end_time',
+ name: 'End Time',
+ minWidth: 120,
+ value: (row: CronJobRun) => <div className="text-xs">{formatDate(row.end_time)}</div>,
+ },
+
+ {
+ id: 'duration',
+ name: 'Duration',
+ minWidth: 100,
+ value: (row: CronJobRun) => (
+ <div className="text-xs">{calculateDuration(row.start_time, row.end_time)}</div>
+ ),
+ },
+]
+
+const columns = cronJobColumns.map((col) => {
+ const result: Column<CronJobRun> = {
+ key: col.id,
+ name: col.name,
+ resizable: true,
+ minWidth: col.minWidth ?? 120,
+ headerCellClass: 'first:pl-6 cursor-pointer',
+ renderHeaderCell: () => {
+ return (
+ <div className="flex items-center justify-between font-mono font-normal text-xs w-full">
+ <div className="flex items-center gap-x-2">
+ <p className="!text-foreground">{col.name}</p>
+ </div>
+ </div>
+ )
+ },
+ renderCell: (props) => {
+ const value = col.value(props.row)
+
+ return (
+ <div
+ className={cn(
+ 'w-full flex flex-col justify-center font-mono text-xs',
+ typeof value === 'number' ? 'text-right' : ''
+ )}
+ >
+ <span>{value}</span>
+ </div>
+ )
+ },
+ }
+ return result
+})
+
+function isAtBottom({ currentTarget }: UIEvent<HTMLDivElement>): boolean {
+ return currentTarget.scrollTop + 10 >= currentTarget.scrollHeight - currentTarget.clientHeight
+}
+
+export const PreviousRunsTab = () => {
+ const { childId: jobName } = useParams()
+ const { project } = useProjectContext()
+
+ const { data: cronJobs, isLoading: isLoadingCronJobs } = useCronJobsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const currentJobState = cronJobs?.find((job) => job.jobname === jobName)
+
+ const {
+ data,
+ isLoading: isLoadingCronJobRuns,
+ fetchNextPage,
+ isFetching,
+ } = useCronJobRunsInfiniteQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ jobId: Number(currentJobState?.jobid),
+ },
+ { enabled: !!currentJobState?.jobid, staleTime: 30 }
+ )
+
+ const handleScroll = useCallback(
+ (event: UIEvent<HTMLDivElement>) => {
+ if (isLoadingCronJobRuns || !isAtBottom(event)) return
+ // the cancelRefetch is to prevent the query from being refetched when the user scrolls back up and down again,
+ // resulting in multiple fetchNextPage calls
+ fetchNextPage({ cancelRefetch: false })
+ },
+ [fetchNextPage, isLoadingCronJobRuns]
+ )
+
+ const cronJobRuns = useMemo(() => data?.pages.flatMap((p) => p) || [], [data?.pages])
+
+ return (
+ <div className="h-full flex flex-col">
+ <div className="mt-4 h-full">
+ <LoadingLine loading={isFetching} />
+ <DataGrid
+ className="flex-grow h-full"
+ rowHeight={44}
+ headerRowHeight={36}
+ onScroll={handleScroll}
+ columns={columns}
+ rows={cronJobRuns ?? []}
+ rowClass={() => {
+ const isSelected = false
+ return cn([
+ `${isSelected ? 'bg-surface-300 dark:bg-surface-300' : 'bg-200'} `,
+ `${isSelected ? '[&>div:first-child]:border-l-4 border-l-secondary [&>div]:border-l-foreground' : ''}`,
+ '[&>.rdg-cell]:border-box [&>.rdg-cell]:outline-none [&>.rdg-cell]:shadow-none',
+ '[&>.rdg-cell:first-child>div]:ml-4',
+ ])
+ }}
+ renderers={{
+ renderRow(_idx, props) {
+ return <Row key={props.row.job_pid} {...props} />
+ },
+ noRowsFallback: isLoadingCronJobRuns ? (
+ <div className="absolute top-14 px-6 w-full">
+ <GenericSkeletonLoader />
+ </div>
+ ) : (
+ <div className="flex items-center justify-center w-full col-span-6">
+ <CronJobsEmptyState page="runs" />
+ </div>
+ ),
+ }}
+ />
+ </div>
+
+ <div className="px-6 py-6 flex gap-12 border-t">
+ {isLoadingCronJobs ? (
+ <GenericSkeletonLoader />
+ ) : (
+ <>
+ <div className="grid gap-2 w-56">
+ <h3 className="text-sm">Schedule</h3>
+ <p className="text-xs text-foreground-light">
+ {currentJobState?.schedule ? (
+ <>
+ <span className="font-mono text-lg">{currentJobState.schedule}</span>
+ <p>
+ {isSecondsFormat(currentJobState.schedule)
+ ? ''
+ : CronToString(currentJobState.schedule.toLowerCase())}
+ </p>
+ </>
+ ) : (
+ <span>Loading schedule...</span>
+ )}
+ </p>
+ </div>
+
+ <div className="grid gap-2">
+ <h3 className="text-sm">Command</h3>
+ <Tooltip_Shadcn_>
+ <TooltipTrigger_Shadcn_ className=" text-left p-0! cursor-pointer truncate max-w-[300px] h-12 relative">
+ <SimpleCodeBlock
+ showCopy={false}
+ className="sql"
+ parentClassName=" [&>div>span]:text-xs bg-alternative-200 !p-2 rounded-md"
+ >
+ {currentJobState?.command}
+ </SimpleCodeBlock>
+ <div className="bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-background-200 to-transparent absolute " />
+ </TooltipTrigger_Shadcn_>
+ <TooltipContent_Shadcn_
+ side="bottom"
+ align="center"
+ className="max-w-[400px] text-wrap"
+ >
+ <SimpleCodeBlock
+ showCopy={false}
+ className="sql"
+ parentClassName=" [&>div>span]:text-xs bg-alternative-200 !p-2 rounded-md"
+ >
+ {currentJobState?.command}
+ </SimpleCodeBlock>
+ </TooltipContent_Shadcn_>
+ </Tooltip_Shadcn_>
+ {/* <div className="text-xs text-foreground-light">
+ <SimpleCodeBlock
+ showCopy={false}
+ className="sql"
+ parentClassName=" [&>div>span]:text-xs bg-alternative-200 !p-2 rounded-md"
+ >
+ {currentJobState?.command}
+ </SimpleCodeBlock>
+ </div> */}
+ </div>
+
+ <div className="grid gap-2">
+ <h3 className="text-sm">Explore</h3>
+ <Button asChild type="outline" icon={<List strokeWidth={1.5} size="14" />}>
+ {/* [Terry] need to link to the exact jobid, but not currently supported */}
+ <Link target="_blank" href={`/project/${project?.ref}/logs/pgcron-logs/`}>
+ View logs
+ </Link>
+ </Button>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/Landing/Integrations.constants.tsx b/apps/studio/components/interfaces/Integrations/Landing/Integrations.constants.tsx
index 1bcaf7b4331..cad9403f5ea 100644
--- a/apps/studio/components/interfaces/Integrations/Landing/Integrations.constants.tsx
+++ b/apps/studio/components/interfaces/Integrations/Landing/Integrations.constants.tsx
@@ -1,4 +1,4 @@
-import { Clock5, Layers, Vault, Webhook } from 'lucide-react'
+import { Clock5, Layers, Timer, Vault, Webhook } from 'lucide-react'
import Image from 'next/image'
import { ComponentType, ReactNode } from 'react'
@@ -131,9 +131,21 @@ const supabaseIntegrations: IntegrationDefinition[] = [
{
route: 'cron-jobs',
label: 'Cron Jobs',
+ hasChild: true,
+ childIcon: (
+ <Timer size={12} strokeWidth={1.5} className={cn('text-foreground w-full h-full')} />
+ ),
},
],
navigate: (id: string, pageId: string = 'overview', childId: string | undefined) => {
+ if (childId) {
+ return dynamic(
+ () => import('../CronJobs/PreviousRunsTab').then((mod) => mod.PreviousRunsTab),
+ {
+ loading: Loading,
+ }
+ )
+ }
switch (pageId) {
case 'overview':
return dynamic(
diff --git a/apps/studio/components/interfaces/Settings/Logs/LogSelection.tsx b/apps/studio/components/interfaces/Settings/Logs/LogSelection.tsx
index fb62e0e5360..1913b4ba78a 100644
--- a/apps/studio/components/interfaces/Settings/Logs/LogSelection.tsx
+++ b/apps/studio/components/interfaces/Settings/Logs/LogSelection.tsx
@@ -42,6 +42,8 @@ const LogSelection = ({ log, onClose, queryType, isLoading, error }: LogSelectio
case 'database':
return <DatabasePostgresSelectionRender log={log} />
+ case 'pg_cron':
+ return <DatabasePostgresSelectionRender log={log} />
case 'fn_edge':
return <FunctionInvocationSelectionRender log={log} />
diff --git a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx
index ba438fac150..f83f79c0f8d 100644
--- a/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx
+++ b/apps/studio/components/interfaces/Settings/Logs/LogTable.tsx
@@ -173,6 +173,9 @@ const LogTable = ({
case 'auth':
columns = AuthColumnRenderer
break
+ case 'pg_cron':
+ columns = DatabasePostgresColumnRender
+ break
default:
if (firstRow && isDefaultLogPreviewFormat(firstRow)) {
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts
index 2da4d335752..4af99e34e51 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts
@@ -260,7 +260,7 @@ from edge_logs f
cross join unnest(m.request) as r
cross join unnest(m.response) as res
cross join unnest(res.headers) as h
-where starts_with(r.path, '/storage/v1/object')
+where starts_with(r.path, '/storage/v1/object')
and r.method = 'GET'
and h.cf_cache_status in ('MISS', 'NONE/UNKNOWN', 'EXPIRED', 'BYPASS', 'DYNAMIC')
group by path, search
@@ -363,7 +363,7 @@ export enum LogsTableName {
POSTGREST = 'postgrest_logs',
SUPAVISOR = 'supavisor_logs',
WAREHOUSE = 'warehouse_logs',
- CRON_JOBS = 'cron_job_run_details',
+ PG_CRON = 'pg_cron_logs',
}
export const LOGS_TABLES = {
@@ -377,7 +377,7 @@ export const LOGS_TABLES = {
postgrest: LogsTableName.POSTGREST,
supavisor: LogsTableName.SUPAVISOR,
warehouse: LogsTableName.WAREHOUSE,
- cron: LogsTableName.CRON_JOBS,
+ pg_cron: LogsTableName.POSTGRES,
}
export const LOGS_SOURCE_DESCRIPTION = {
@@ -391,7 +391,7 @@ export const LOGS_SOURCE_DESCRIPTION = {
[LogsTableName.POSTGREST]: 'RESTful API web server logs',
[LogsTableName.SUPAVISOR]: 'Cloud-native Postgres connection pooler logs',
[LogsTableName.WAREHOUSE]: 'Logs obtained from a data warehouse collection',
- [LogsTableName.CRON_JOBS]: 'Logs obtained from cron job runs',
+ [LogsTableName.PG_CRON]: 'Postgres logs from pg_cron cron jobs',
}
export const genQueryParams = (params: { [k: string]: string }) => {
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.types.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.types.ts
index 3ba1eef4fb8..565c00e41b1 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.types.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.types.ts
@@ -88,7 +88,7 @@ export type QueryType =
| 'supavisor'
| 'postgrest'
| 'warehouse'
- | 'cron'
+ | 'pg_cron'
export type Mode = 'simple' | 'custom'
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
index 6a4c84ec55c..7367bf296ee 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
@@ -145,8 +145,8 @@ export const genDefaultQuery = (table: LogsTableName, filters: Filters, limit: n
if (IS_PLATFORM === false) {
return `
-- local dev edge_logs query
-select id, edge_logs.timestamp, event_message, request.method, request.path, response.status_code
-from edge_logs
+select id, edge_logs.timestamp, event_message, request.method, request.path, response.status_code
+from edge_logs
${joins}
${where}
${orderBy}
@@ -212,8 +212,19 @@ limit ${limit}
limit ${limit}
`
- case 'cron_job_run_details':
- return `select status, start_time, end_time, jobid from ${table} ${where} ${orderBy} limit ${limit}`
+ case 'pg_cron_logs':
+ const baseWhere = `where (parsed.application_name = 'pg_cron' OR event_message LIKE '%cron job%')`
+
+ const pgCronWhere = where ? `${baseWhere} AND ${where.substring(6)}` : baseWhere
+
+ return `select identifier, postgres_logs.timestamp, id, event_message, parsed.error_severity, parsed.query
+from postgres_logs
+ cross join unnest(metadata) as m
+ cross join unnest(m.parsed) as parsed
+${pgCronWhere}
+${orderBy}
+limit ${limit}
+`
}
}
diff --git a/apps/studio/components/layouts/LogsLayout/LogsSidebarMenuV2.tsx b/apps/studio/components/layouts/LogsLayout/LogsSidebarMenuV2.tsx
index 0eda209a230..d24b38bfa3f 100644
--- a/apps/studio/components/layouts/LogsLayout/LogsSidebarMenuV2.tsx
+++ b/apps/studio/components/layouts/LogsLayout/LogsSidebarMenuV2.tsx
@@ -166,8 +166,8 @@ export function LogsSidebarMenuV2() {
},
{
name: 'Cron Jobs',
- key: 'cron-logs',
- url: `/project/${ref}/logs/cron-logs`,
+ key: 'pg_cron',
+ url: `/project/${ref}/logs/pgcron-logs`,
items: [],
},
]
diff --git a/apps/studio/data/database-cron-jobs/database-cron-jobs-runs-infinite-query.ts b/apps/studio/data/database-cron-jobs/database-cron-jobs-runs-infinite-query.ts
new file mode 100644
index 00000000000..d52865cf607
--- /dev/null
+++ b/apps/studio/data/database-cron-jobs/database-cron-jobs-runs-infinite-query.ts
@@ -0,0 +1,84 @@
+import { UseInfiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
+import { last } from 'lodash'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import { ResponseError } from 'types'
+import { databaseCronJobsKeys } from './keys'
+
+export type DatabaseCronJobRunsVariables = {
+ projectRef?: string
+ connectionString?: string
+ jobId: number
+}
+
+export type CronJobRun = {
+ jobid: number
+ runid: number
+ job_pid: number
+ database: string
+ username: string
+ command: string
+ status: 'succeeded' | 'failed'
+ return_message: string
+ start_time: string
+ end_time: string
+}
+
+export const CRON_JOB_RUNS_PAGE_SIZE = 30
+
+export async function getDatabaseCronJobRuns({
+ projectRef,
+ connectionString,
+ jobId,
+ afterTimestamp,
+}: DatabaseCronJobRunsVariables & { afterTimestamp: string }) {
+ if (!projectRef) throw new Error('Project ref is required')
+
+ let query = `
+ SELECT * FROM cron.job_run_details
+ WHERE
+ jobid = '${jobId}'
+ ${afterTimestamp ? `AND start_time < '${afterTimestamp}'` : ''}
+ ORDER BY start_time DESC
+ LIMIT ${CRON_JOB_RUNS_PAGE_SIZE}`
+
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: query,
+ })
+ return result
+}
+
+export type DatabaseCronJobData = CronJobRun[]
+export type DatabaseCronJobError = ResponseError
+
+export const useCronJobRunsInfiniteQuery = <TData = DatabaseCronJobData>(
+ { projectRef, connectionString, jobId }: DatabaseCronJobRunsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseInfiniteQueryOptions<DatabaseCronJobData, DatabaseCronJobError, TData> = {}
+) =>
+ useInfiniteQuery<DatabaseCronJobData, DatabaseCronJobError, TData>(
+ databaseCronJobsKeys.runsInfinite(projectRef, jobId, { status }),
+ ({ pageParam }) => {
+ return getDatabaseCronJobRuns({
+ projectRef,
+ connectionString,
+ jobId,
+ afterTimestamp: pageParam,
+ })
+ },
+ {
+ staleTime: 0,
+ enabled: enabled && typeof projectRef !== 'undefined',
+
+ getNextPageParam(lastPage) {
+ const hasNextPage = lastPage.length <= CRON_JOB_RUNS_PAGE_SIZE
+ if (!hasNextPage) return undefined
+ return last(lastPage)?.start_time
+ },
+ ...options,
+ }
+ )
diff --git a/apps/studio/data/database-cron-jobs/keys.ts b/apps/studio/data/database-cron-jobs/keys.ts
index 5df1b7ec631..f132226a3d8 100644
--- a/apps/studio/data/database-cron-jobs/keys.ts
+++ b/apps/studio/data/database-cron-jobs/keys.ts
@@ -3,5 +3,12 @@ export const databaseCronJobsKeys = {
delete: () => ['cron-jobs', 'delete'] as const,
alter: () => ['cronjobs', 'alter'] as const,
list: (projectRef: string | undefined) => ['projects', projectRef, 'cron-jobs'] as const,
+ runsInfinite: (projectRef: string | undefined, jobId: number, options?: object) => [
+ 'projects',
+ projectRef,
+ 'cron-jobs',
+ jobId,
+ options,
+ ],
timezone: (projectRef: string | undefined) => ['database-cron-timezone', projectRef] as const,
}
diff --git a/apps/studio/hooks/analytics/useLogsQuery.tsx b/apps/studio/hooks/analytics/useLogsQuery.tsx
index 9f3bf306dbe..0452722bb38 100644
--- a/apps/studio/hooks/analytics/useLogsQuery.tsx
+++ b/apps/studio/hooks/analytics/useLogsQuery.tsx
@@ -55,7 +55,6 @@ const useLogsQuery = (
const usesWith = checkForWithClause(params.sql || '')
const usesILIKE = checkForILIKEClause(params.sql || '')
- const usesWildcard = checkForWildcard(params.sql || '')
const {
data,
@@ -94,13 +93,6 @@ const useLogsQuery = (
docs: 'https://supabase.com/docs/guides/platform/advanced-log-filtering#the-ilike-and-similar-to-keywords-are-not-supported',
}
}
- if (usesWildcard) {
- error = {
- message:
- 'Wildcard (*) queries are not supported. Please remove the wildcard and try again.',
- docs: 'https://supabase.com/docs/guides/platform/advanced-log-filtering#the-wildcard-operator--to-select-columns-is-not-supported',
- }
- }
}
const changeQuery = (newQuery = '') => {
setParams((prev) => ({ ...prev, sql: newQuery }))
diff --git a/apps/studio/pages/project/[ref]/logs/cron-logs.tsx b/apps/studio/pages/project/[ref]/logs/cron-logs.tsx
index cb80975342b..d6a549a1394 100644
--- a/apps/studio/pages/project/[ref]/logs/cron-logs.tsx
+++ b/apps/studio/pages/project/[ref]/logs/cron-logs.tsx
@@ -15,8 +15,8 @@ export const LogPage: NextPageWithLayout = () => {
<LogsPreviewer
projectRef={ref as string}
condensedLayout={true}
- tableName={LogsTableName.CRON_JOBS}
- queryType={'cron'}
+ tableName={LogsTableName.PG_CRON}
+ queryType={'pg_cron'}
/>
)
}
diff --git a/apps/studio/pages/project/[ref]/logs/pgcron-logs.tsx b/apps/studio/pages/project/[ref]/logs/pgcron-logs.tsx
new file mode 100644
index 00000000000..25ba5c01e35
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/logs/pgcron-logs.tsx
@@ -0,0 +1,24 @@
+import { useRouter } from 'next/router'
+
+import { LogsTableName } from 'components/interfaces/Settings/Logs/Logs.constants'
+import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'
+import LogsLayout from 'components/layouts/LogsLayout/LogsLayout'
+import type { NextPageWithLayout } from 'types'
+
+export const LogPage: NextPageWithLayout = () => {
+ const router = useRouter()
+ const { ref } = router.query
+
+ return (
+ <LogsPreviewer
+ condensedLayout
+ queryType="pg_cron"
+ projectRef={ref as string}
+ tableName={LogsTableName.PG_CRON}
+ />
+ )
+}
+
+LogPage.getLayout = (page) => <LogsLayout title="PgCron Logs">{page}</LogsLayout>
+
+export default LogPage
diff --git a/package.json b/package.json
index e9361b69657..82a14eb6657 100644
--- a/package.json
+++ b/package.json
@@ -5,12 +5,7 @@
"author": "Supabase, Inc.",
"license": "Apache-2.0",
"private": true,
- "workspaces": [
- "apps/*",
- "tests",
- "playwright-tests",
- "packages/*"
- ],
+ "workspaces": ["apps/*", "tests", "playwright-tests", "packages/*"],
"scripts": {
"build": "turbo run build",
"build:studio": "turbo run build --filter=studio",
@@ -58,13 +53,6 @@
"npm": "^10.0.0",
"node": "^20.0.0"
},
- "keywords": [
- "postgres",
- "firebase",
- "storage",
- "functions",
- "database",
- "auth"
- ],
+ "keywords": ["postgres", "firebase", "storage", "functions", "database", "auth"],
"packageManager": "[email protected]"
}