mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
fix(studio): keep a cron job's stored command when opening the editor (#53172)
## Problem
The cron job editor could rewrite a job's SQL just by opening it, and
the result depended on how the editor was opened:
- Opened from the jobs list ("..." menu > Edit), the sheet is already
mounted with an empty job. Opening it resets the form to the parsed
values, which re-runs the effect that rebuilds `values.snippet` from the
form fields. The stored command gets replaced by a regenerated one.
- Opened from the job's own page, the sheet mounts with the job, so the
fields don't change on open and the stored command is kept.
The regenerated command is lossy for `net.http_*` calls the HTTP form
can't represent. For example, a header value such as `'Bearer ' ||
(select decrypted_secret from vault.decrypted_secrets ...)` turned into
a literal JSON string, and a chained `|| jsonb_build_object(...)` was
dropped. Saving would silently overwrite a working job.
## Solution
- `parseCronJobCommand` now checks that a `net.http_get` /
`net.http_post` command can be represented by the HTTP form before
parsing it into fields. It needs named arguments only (`url`, `headers`,
`body`, `timeout_milliseconds`), literal values (headers may also be a
single `jsonb_build_object` of literals), and nothing after the call
besides `;`. Anything else (SQL expressions, `||` concatenation, unknown
arguments such as `params`, extra statements) opens as a SQL snippet
with the stored command unchanged. The argument splitter used for
`jsonb_build_object` is generalised and reused for this check.
- `CreateCronJobSheet` keeps the stored command while the form fields
still describe it. It compares the command built from the current fields
with the one built from the parsed stored values. The SQL is regenerated
only after a field actually changes, so both ways of opening the editor
behave the same.
## How to verify
On a project with `pg_cron` and `pg_net` enabled, create a cron job (via
the SQL editor) whose command is a `net.http_post` with headers that use
a SQL expression, for example:
```sql
select cron.schedule('expr-headers', '*/5 * * * *', $$
select net.http_post(
url:='https://example.com/hook',
headers:=jsonb_build_object('Authorization', 'Bearer ' || (select current_user)) || jsonb_build_object('x-fired-at', to_char(now(), 'YYYY')),
body:='{}'::jsonb,
timeout_milliseconds:=5000
);
$$);
```
- Integrations > Cron > Jobs, "..." menu on the job > Edit: the editor
opens as a SQL snippet showing exactly the stored command.
- Click the job row to open its page, then Edit: the editor shows the
same command.
- Edit a simple HTTP job (literal URL and headers) from both places: it
opens in the HTTP request / Edge Function form, and the SQL preview
equals the stored command until a field is changed.
- Change a header value in that simple job: the SQL preview updates to
reflect the change.
Checks run: `vitest run components/interfaces/Integrations/CronJobs`
(new fallback cases in `CronJobs.utils.test.ts`), `pnpm turbo run
typecheck --filter='...[origin/master]'`, eslint and prettier on the
changed files.
[FE-4980](https://linear.app/supabase/issue/FE-4980/fix-cron-job-editor-serialization-different-sql-generated-for-menu-vs)
---------
Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
ba94909a8c
commit
5f77aa07ea
3 files changed
+89
-20
No files matched your search
+5
-3
@@ -258,9 +258,11 @@ export const CreateCronJobSheet = ({ open, selectedCronJob, onClose }: CreateCro
|
||||
endpoint,
|
||||
snippet: '',
|
||||
})
|
||||
if (command) {
|
||||
form.setValue('values.snippet', command)
|
||||
}
|
||||
if (!command) return
|
||||
|
||||
// Keep the stored command until a field changes
|
||||
const isStoredCommand = isEditing && command === buildCommand(cronJobValues)
|
||||
form.setValue('values.snippet', isStoredCommand ? cronJobValues.snippet : command)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [
|
||||
cronType,
|
||||
|
||||
@@ -65,6 +65,26 @@ describe('parseCronJobCommand', () => {
|
||||
case: 'an HTTP request in positional notation',
|
||||
command: `SELECT net.http_post( 'https://webhook.site/dacc2028-a588-462c-9597-c8968e61d0fa', '{"message":"Hello from Supabase"}'::jsonb, '{}'::jsonb, '{"Content-Type":"application/json"}'::jsonb );`,
|
||||
},
|
||||
{
|
||||
case: 'an HTTP request whose header value is a SQL expression',
|
||||
command: `select net.http_post( url:='https://random_project_ref.supabase.co/functions/v1/_', headers:=jsonb_build_object('Authorization', 'Bearer ' || (SELECT decrypted_secret FROM vault.decrypted_secrets WHERE name = 'secret')), body:='{}'::jsonb, timeout_milliseconds:=5000 );`,
|
||||
},
|
||||
{
|
||||
case: 'an HTTP request with concatenated header objects',
|
||||
command: `select net.http_post( url:='https://example.com/api', headers:=jsonb_build_object('a', '1') || jsonb_build_object('b', to_char(now(), 'YYYY')), timeout_milliseconds:=5000 );`,
|
||||
},
|
||||
{
|
||||
case: 'an HTTP request with a non-literal body',
|
||||
command: `select net.http_post( url:='https://example.com/api', body:=jsonb_build_object('at', now()), timeout_milliseconds:=5000 );`,
|
||||
},
|
||||
{
|
||||
case: 'an HTTP request with an argument the form does not support',
|
||||
command: `select net.http_get( url:='https://example.com/api', params:=jsonb_build_object('a', '1') );`,
|
||||
},
|
||||
{
|
||||
case: 'an HTTP request followed by another statement',
|
||||
command: `select net.http_get( url:='https://example.com/api' ); select 1;`,
|
||||
},
|
||||
])('falls back to a sql snippet for $case', ({ command }) => {
|
||||
expect(parseCronJobCommand(command, REF)).toStrictEqual({
|
||||
type: 'sql_snippet',
|
||||
|
||||
@@ -28,27 +28,22 @@ const unwrapSqlLiteral = (token: string) => {
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits the argument list of a `jsonb_build_object(...)` call into its individual
|
||||
* values, honoring single-quoted SQL string literals (with '' escapes) and nested
|
||||
* parentheses. A naive split on ',' corrupts a header name or value that legitimately
|
||||
* contains a comma or parenthesis, which then gets persisted on save and no longer
|
||||
* matches what the user entered.
|
||||
* Splits a SQL argument list starting after its `(`, respecting quotes and nested parentheses.
|
||||
* Returns the raw arguments and the index of the closing `)`, or undefined if unbalanced.
|
||||
*/
|
||||
const parseJsonBuildObjectArgs = (command: string) => {
|
||||
const match = command.match(/headers:=jsonb_build_object\s*\(/i)
|
||||
if (!match || match.index === undefined) return []
|
||||
|
||||
const splitSqlArgs = (sql: string, start: number) => {
|
||||
const args: string[] = []
|
||||
let current = ''
|
||||
let depth = 1
|
||||
let inQuote = false
|
||||
let hasContent = false
|
||||
let i = start
|
||||
|
||||
for (let i = match.index + match[0].length; i < command.length && depth > 0; i++) {
|
||||
const char = command[i]
|
||||
for (; i < sql.length; i++) {
|
||||
const char = sql[i]
|
||||
|
||||
if (inQuote) {
|
||||
if (char === "'" && command[i + 1] === "'") {
|
||||
if (char === "'" && sql[i + 1] === "'") {
|
||||
current += "''"
|
||||
i++
|
||||
continue
|
||||
@@ -67,7 +62,8 @@ const parseJsonBuildObjectArgs = (command: string) => {
|
||||
current += char
|
||||
} else if (char === ')') {
|
||||
depth--
|
||||
if (depth > 0) current += char
|
||||
if (depth === 0) break
|
||||
current += char
|
||||
} else if (char === ',' && depth === 1) {
|
||||
args.push(current)
|
||||
current = ''
|
||||
@@ -77,12 +73,60 @@ const parseJsonBuildObjectArgs = (command: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Unbalanced parentheses: bail rather than emit mangled fragments.
|
||||
if (depth !== 0) return []
|
||||
if (depth !== 0) return undefined
|
||||
|
||||
if (hasContent || args.length > 0) args.push(current)
|
||||
|
||||
return args.map(unwrapSqlLiteral)
|
||||
return { args, end: i }
|
||||
}
|
||||
|
||||
const parseJsonBuildObjectArgs = (command: string) => {
|
||||
const match = command.match(/headers:=jsonb_build_object\s*\(/i)
|
||||
if (!match || match.index === undefined) return []
|
||||
|
||||
const result = splitSqlArgs(command, match.index + match[0].length)
|
||||
return result ? result.args.map(unwrapSqlLiteral) : []
|
||||
}
|
||||
|
||||
const SQL_STRING_LITERAL = /^e?'(?:''|[^'])*'$/i
|
||||
const SQL_STRING_LITERAL_WITH_CAST = /^e?'(?:''|[^'])*'(?:\s*::\s*(?:jsonb|json|text))?$/i
|
||||
|
||||
const isJsonBuildObjectOfLiterals = (value: string) => {
|
||||
const match = value.match(/^jsonb_build_object\s*\(/i)
|
||||
if (!match) return false
|
||||
const result = splitSqlArgs(value, match[0].length)
|
||||
if (!result || value.slice(result.end + 1).trim().length > 0) return false
|
||||
return result.args.every((arg) => SQL_STRING_LITERAL.test(arg.trim()))
|
||||
}
|
||||
|
||||
// The HTTP form rebuilds the command from its fields, so anything else is edited as a SQL snippet
|
||||
const isFormRepresentableHttpCommand = (command: string) => {
|
||||
const match = command.match(/^select\s+net\.(http_get|http_post)\s*\(/i)
|
||||
if (!match) return false
|
||||
|
||||
const result = splitSqlArgs(command, match[0].length)
|
||||
if (!result) return false
|
||||
if (!/^\s*;?\s*$/.test(command.slice(result.end + 1))) return false
|
||||
|
||||
return result.args.every((arg) => {
|
||||
const namedArg = arg.trim().match(/^([a-z_]+)\s*:=\s*([\s\S]*)$/i)
|
||||
if (!namedArg) return false
|
||||
const name = namedArg[1].toLowerCase()
|
||||
const value = namedArg[2].trim()
|
||||
|
||||
switch (name) {
|
||||
case 'url':
|
||||
return SQL_STRING_LITERAL.test(value)
|
||||
case 'body':
|
||||
return SQL_STRING_LITERAL_WITH_CAST.test(value)
|
||||
case 'headers':
|
||||
return SQL_STRING_LITERAL_WITH_CAST.test(value) || isJsonBuildObjectOfLiterals(value)
|
||||
case 'timeout_milliseconds':
|
||||
return /^\d+$/.test(value)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function buildCronCreateQuery(
|
||||
@@ -142,7 +186,10 @@ export const parseCronJobCommand = (
|
||||
): CronJobType => {
|
||||
const command = originalCommand.replaceAll('$$', ' ').replaceAll(/\n/g, ' ').trim()
|
||||
|
||||
if (command.toLocaleLowerCase().match(/^select\s+net\./)) {
|
||||
if (
|
||||
command.toLocaleLowerCase().match(/^select\s+net\./) &&
|
||||
isFormRepresentableHttpCommand(command)
|
||||
) {
|
||||
const methodMatch = command.match(/select\s+net\.([^']+)\(\s*url:=/i)
|
||||
const method = methodMatch?.[1] || ''
|
||||
|
||||
|
||||
Reference in new issue
Block a user