The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): log_sql content shape + remap content.sql to unchecked_sql (#48305)
Charis7743fee3aba2
diff --git a/apps/studio/components/interfaces/SQLEditor/MoveQueryModal.tsx b/apps/studio/components/interfaces/SQLEditor/MoveQueryModal.tsxindex bb300f5beed..13e8122e793 100644--- a/apps/studio/components/interfaces/SQLEditor/MoveQueryModal.tsx+++ b/apps/studio/components/interfaces/SQLEditor/MoveQueryModal.tsx@@ -37,7 +37,7 @@ import {} from 'ui'import * as z from 'zod'-import { getContentById } from '@/data/content/content-id-query'+import { getSqlSnippetById } from '@/data/content/content-id-query'import { useContentUpsertMutation } from '@/data/content/content-upsert-mutation'import { useSQLSnippetFolderCreateMutation } from '@/data/content/sql-folder-create-mutation'import { Snippet } from '@/data/content/sql-folders-query'@@ -136,10 +136,9 @@ export const MoveQueryModal = ({ visible, snippets = [], onClose }: MoveQueryModsnippets.map(async (snippet) => {let snippetContent = (snippet as SnippetWithContent)?.contentif (snippetContent === undefined) {- const { content } = await getContentById({ projectRef: ref, id: snippet.id })- if ('unchecked_sql' in content) {- snippetContent = content- }+ // Move only ever operates on database SQL snippets+ const { content } = await getSqlSnippetById({ projectRef: ref, id: snippet.id })+ snippetContent = content}if (snippetContent === undefined) {@@ -156,7 +155,7 @@ export const MoveQueryModal = ({ visible, snippets = [], onClose }: MoveQueryModproject_id: snippet.project_id,owner_id: snippet.owner_id,folder_id: selectedId === 'root' ? null : folderId,- content: snippetContent as any,+ content: snippetContent,},})if (IS_PLATFORM) {diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.SavedQueriesItem.test.tsx b/apps/studio/components/interfaces/Settings/Logs/Logs.SavedQueriesItem.test.tsxnew file mode 100644index 00000000000..1adbd15c8e5--- /dev/null+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.SavedQueriesItem.test.tsx@@ -0,0 +1,70 @@+import { fireEvent, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { mockAnimationsApi } from 'jsdom-testing-mocks'+import { HttpResponse } from 'msw'+import { describe, expect, it } from 'vitest'++import { SavedQueriesItem } from './Logs.SavedQueriesItem'+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'+import { customRender } from '@/tests/lib/custom-render'+import { addAPIMock } from '@/tests/lib/msw'++// SavedQueriesItem renders a Radix dropdown + dialog, both of which use Web Animations.+mockAnimationsApi()++const ITEM_ID = 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22'+const LOGS_SQL =+ "select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10"++const item = {+ id: ITEM_ID,+ name: 'My logs query',+ description: 'A saved logs query',+ owner_id: 1,+ content: { unchecked_sql: untrustedLogSql(LOGS_SQL) },+}++describe('SavedQueriesItem', () => {+ it('preserves content.sql (as the raw wire field) and keeps type log_sql when editing a saved logs query', async () => {+ const requests: Array<{ type: string; name: string; content: Record<string, unknown> }> = []+ addAPIMock({+ method: 'put',+ path: '/platform/projects/:ref/content',+ response: async ({ request }) => {+ requests.push(+ (await request.json()) as { type: string; name: string; content: Record<string, unknown> }+ )+ return HttpResponse.json({+ id: ITEM_ID,+ type: 'log_sql',+ name: 'My logs query (edited)',+ description: 'A saved logs query',+ visibility: 'user',+ owner_id: 1,+ project_id: 1,+ folder_id: null,+ inserted_at: '2024-01-01T00:00:00.000Z',+ updated_at: '2024-01-01T00:00:00.000Z',+ content: { sql: LOGS_SQL, content_id: ITEM_ID, schema_version: '1' },+ })+ },+ })++ customRender(<SavedQueriesItem item={item} />)++ // Open the actions dropdown, then the edit modal.+ await userEvent.click(screen.getByRole('button', { name: 'Actions' }))+ await userEvent.click(await screen.findByText('Edit query'))++ // Dirty the form so the submit button enables, then submit.+ await userEvent.type(await screen.findByPlaceholderText('Enter text'), ' (edited)')+ fireEvent.click(screen.getByRole('button', { name: 'Save query' }))++ await waitFor(() => expect(requests).toHaveLength(1))++ expect(requests[0].type).toBe('log_sql')+ expect(requests[0].name).toBe('My logs query (edited)')+ expect(requests[0].content.sql).toBe(LOGS_SQL)+ expect(requests[0].content).not.toHaveProperty('unchecked_sql')+ })+})diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.SavedQueriesItem.tsx b/apps/studio/components/interfaces/Settings/Logs/Logs.SavedQueriesItem.tsxindex ac160baa964..97831f24449 100644--- a/apps/studio/components/interfaces/Settings/Logs/Logs.SavedQueriesItem.tsx+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.SavedQueriesItem.tsx@@ -12,6 +12,7 @@ import { UpdateSavedQueryModal } from './Logs.UpdateSavedQueryModal'import { LogsSidebarItem } from './SidebarV2/SidebarItem'import { useContentDeleteMutation } from '@/data/content/content-delete-mutation'import { useContentUpsertMutation } from '@/data/content/content-upsert-mutation'+import type { UntrustedLogSqlFragment } from '@/data/logs/safe-analytics-sql'interface SavedQueriesItemProps {item: {@@ -20,7 +21,7 @@ interface SavedQueriesItemProps {description?: stringowner_id: numbercontent: {- sql: string+ unchecked_sql: UntrustedLogSqlFragment}}}@@ -87,7 +88,7 @@ export const SavedQueriesItem = ({ item }: SavedQueriesItemProps) => {<LogsSidebarItemlabel={item.name}icon={<SqlEditor size="15" />}- href={`/project/${ref}/logs/explorer?queryId=${encodeURIComponent(item.id)}&q=${encodeURIComponent(item.content.sql)}`}+ href={`/project/${ref}/logs/explorer?queryId=${encodeURIComponent(item.id)}&q=${encodeURIComponent(item.content.unchecked_sql)}`}isActive={isActive}dropdownItems={<>diff --git a/apps/studio/components/interfaces/Settings/Logs/RecentQueriesItem.tsx b/apps/studio/components/interfaces/Settings/Logs/RecentQueriesItem.tsxindex d0fdb2505ed..62c93b2d8d7 100644--- a/apps/studio/components/interfaces/Settings/Logs/RecentQueriesItem.tsx+++ b/apps/studio/components/interfaces/Settings/Logs/RecentQueriesItem.tsx@@ -15,18 +15,18 @@ const RecentQueriesItem: React.FC<Props> = ({ item }) => {const { ref } = router.queryreturn (- <Table.tr key={item.sql}>+ <Table.tr key={item.unchecked_sql}><Table.tdclassName={`expanded-row-content border-l border-r bg-alternative px-3! pt-0! pb-0! transition-all`}>- <SqlSnippetCode>{item.sql}</SqlSnippetCode>+ <SqlSnippetCode>{item.unchecked_sql}</SqlSnippetCode></Table.td><Table.td className="text-right"><Buttonvariant="primary"iconRight={<Play size={10} />}onClick={() =>- router.push(`/project/${ref}/logs/explorer?q=${encodeURIComponent(item.sql)}`)+ router.push(`/project/${ref}/logs/explorer?q=${encodeURIComponent(item.unchecked_sql)}`)}>Rundiff --git a/apps/studio/components/interfaces/Settings/Logs/useRecentLogSqlSnippets.test.ts b/apps/studio/components/interfaces/Settings/Logs/useRecentLogSqlSnippets.test.tsnew file mode 100644index 00000000000..05111af5b9d--- /dev/null+++ b/apps/studio/components/interfaces/Settings/Logs/useRecentLogSqlSnippets.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest'++import { normalizeRecentLogSqlSnippet } from './useRecentLogSqlSnippets'+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'++const SQL = "select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10"++describe('normalizeRecentLogSqlSnippet', () => {+ it('brands a legacy raw `sql` entry into `unchecked_sql`', () => {+ const result = normalizeRecentLogSqlSnippet({+ content_id: 'a',+ schema_version: '1',+ sql: SQL,+ })++ expect(result).toEqual({+ content_id: 'a',+ schema_version: '1',+ unchecked_sql: untrustedLogSql(SQL),+ })+ expect(result).not.toHaveProperty('sql')+ })++ it('preserves an already-branded `unchecked_sql` entry', () => {+ const result = normalizeRecentLogSqlSnippet({+ content_id: 'b',+ schema_version: '1',+ unchecked_sql: untrustedLogSql(SQL),+ })++ expect(result).toEqual({+ content_id: 'b',+ schema_version: '1',+ unchecked_sql: untrustedLogSql(SQL),+ })+ expect(result).not.toHaveProperty('sql')+ })++ it('defaults to an empty branded string when neither field is present', () => {+ const result = normalizeRecentLogSqlSnippet({ content_id: 'c', schema_version: '1' })++ expect(result.unchecked_sql).toEqual(untrustedLogSql(''))+ })+})diff --git a/apps/studio/components/interfaces/Settings/Logs/useRecentLogSqlSnippets.ts b/apps/studio/components/interfaces/Settings/Logs/useRecentLogSqlSnippets.tsnew file mode 100644index 00000000000..1c4a5093124--- /dev/null+++ b/apps/studio/components/interfaces/Settings/Logs/useRecentLogSqlSnippets.ts@@ -0,0 +1,47 @@+import { useMemo } from 'react'++import { untrustedLogSql, type UntrustedLogSqlFragment } from '@/data/logs/safe-analytics-sql'+import { useLocalStorage } from '@/hooks/misc/useLocalStorage'+import type { LogSqlSnippets } from '@/types'++/**+ * Shape of a recent-log-sql entry as it may exist in localStorage. Entries written before the+ * `sql` → `unchecked_sql` rename carry the raw `sql` field; entries written after carry the+ * branded `unchecked_sql`. This tolerant type lets us read both and normalize to the branded+ * frontend shape, so no consumer ever sees an unbranded `sql`.+ */+type StoredRecentLogSqlSnippet = Omit<LogSqlSnippets.Content, 'unchecked_sql'> & {+ unchecked_sql?: UntrustedLogSqlFragment+ sql?: string+}++/**+ * Normalizes a stored recent-log-sql entry into the current `LogSqlSnippets.Content` shape,+ * branding a legacy raw `sql` value with `untrustedLogSql`. Prefers an already-branded+ * `unchecked_sql` when present.+ */+export function normalizeRecentLogSqlSnippet(+ entry: StoredRecentLogSqlSnippet+): LogSqlSnippets.Content {+ const { sql, unchecked_sql, ...rest } = entry+ return { ...rest, unchecked_sql: unchecked_sql ?? untrustedLogSql(sql ?? '') }+}++/**+ * localStorage-backed list of recent Logs Explorer queries, always surfaced with the branded+ * `unchecked_sql` field. Reads tolerate the pre-rename `{ sql }` shape and normalize it; writing+ * the normalized value back heals the stored entries over time.+ */+export function useRecentLogSqlSnippets(projectRef?: string) {+ const [stored, setStored] = useLocalStorage<StoredRecentLogSqlSnippet[]>(+ `project-content-${projectRef}-recent-log-sql`,+ []+ )++ const snippets = useMemo<LogSqlSnippets.Content[]>(+ () => stored.map(normalizeRecentLogSqlSnippet),+ [stored]+ )++ return [snippets, setStored] as const+}diff --git a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx b/apps/studio/components/ui/EditorPanel/EditorPanel.tsxindex 036c73653d3..f4a244209b2 100644--- a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx+++ b/apps/studio/components/ui/EditorPanel/EditorPanel.tsx@@ -640,7 +640,7 @@ export const EditorPanel = () => {owner_id: profile.id,content: {...activeSnippet.content,- sql: currentValue,+ unchecked_sql: untrustedSql(currentValue),},},})diff --git a/apps/studio/data/content/content-remap.test.ts b/apps/studio/data/content/content-remap.test.tsindex c2fa305e6e2..d14e5e283a8 100644--- a/apps/studio/data/content/content-remap.test.ts+++ b/apps/studio/data/content/content-remap.test.ts@@ -1,7 +1,8 @@import { untrustedSql } from '@supabase/pg-meta'-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { remapSqlContentField, remapSqlContentFields, unmapSqlContentField } from './content-remap'+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'const SQL_SNIPPET = {id: 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',@@ -14,6 +15,21 @@ const SQL_SNIPPET = {},}+const LOG_SQL_SNIPPET = {+ id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',+ type: 'log_sql' as const,+ name: 'My logs query',+ content: {+ sql: "select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10",+ content_id: 'b1ffcd88-8d1a-4de7-aa5c-5aa8ac270b22',+ schema_version: '1',+ },+}++afterEach(() => {+ vi.unstubAllEnvs()+})+describe('remapSqlContentField', () => {it('remaps content.sql to content.unchecked_sql for SQL snippets', () => {const result = remapSqlContentField(SQL_SNIPPET)@@ -26,6 +42,17 @@ describe('remapSqlContentField', () => {expect(result.content).not.toHaveProperty('sql')})+ it('remaps content.sql to content.unchecked_sql for log_sql snippets using the logs brand', () => {+ const result = remapSqlContentField(LOG_SQL_SNIPPET)++ expect(result.content).toEqual({+ content_id: LOG_SQL_SNIPPET.content.content_id,+ schema_version: '1',+ unchecked_sql: untrustedLogSql(LOG_SQL_SNIPPET.content.sql),+ })+ expect(result.content).not.toHaveProperty('sql')+ })+it('leaves non-SQL content types unchanged', () => {const report = { id: '1', type: 'report' as const, content: { foo: 'bar' } }@@ -77,27 +104,75 @@ describe('unmapSqlContentField', () => {expect(result.content).not.toHaveProperty('unchecked_sql')})+ it('remaps content.unchecked_sql back to content.sql for log_sql snippets', () => {+ const snippet = remapSqlContentField(LOG_SQL_SNIPPET)++ const result = unmapSqlContentField(snippet)++ expect(result.content).toEqual({+ content_id: LOG_SQL_SNIPPET.content.content_id,+ schema_version: '1',+ sql: LOG_SQL_SNIPPET.content.sql,+ })+ expect(result.content).not.toHaveProperty('unchecked_sql')+ })+it('leaves non-SQL content types unchanged', () => {const report = { id: '1', type: 'report' as const, content: { foo: 'bar' } }expect(unmapSqlContentField(report)).toBe(report)})- it('leaves SQL snippets whose content has no unchecked_sql field unchanged', () => {+ it('leaves content without a sql or unchecked_sql field unchanged (never fabricates sql)', () => {const snippet = {id: '1',type: 'sql' as const,- content: { content_id: '1', schema_version: '1.0', sql: 'SELECT 1' },+ content: { content_id: '1', schema_version: '1.0' },}- expect(unmapSqlContentField(snippet)).toBe(snippet)+ const result = unmapSqlContentField(snippet)++ expect(result).toBe(snippet)+ expect(result.content).not.toHaveProperty('sql')+ })++ it('throws in development when content still carries a raw sql field (missed rename)', () => {+ const snippet = {+ id: '1',+ type: 'log_sql' as const,+ content: { content_id: '1', schema_version: '1', sql: 'select 1' },+ }++ expect(() => unmapSqlContentField(snippet)).toThrow(/not migrated/)+ })++ it('never clobbers a raw sql field in production (defensive no-op)', () => {+ vi.stubEnv('NODE_ENV', 'production')+ const snippet = {+ id: '1',+ type: 'log_sql' as const,+ content: { content_id: '1', schema_version: '1', sql: 'select 1' },+ }++ const result = unmapSqlContentField(snippet)++ // The pre-rename `{ sql }` shape is already the wire shape, so passing it through+ // untouched is correct — and crucially avoids writing `sql: undefined`.+ expect(result).toBe(snippet)+ expect(result.content.sql).toBe('select 1')})})describe('remap/unmap round-trip', () => {- it('returns the original content shape after remap then unmap', () => {+ it('returns the original content shape after remap then unmap for sql snippets', () => {const result = unmapSqlContentField(remapSqlContentField(SQL_SNIPPET))expect(result.content).toEqual(SQL_SNIPPET.content)})++ it('returns the original content shape after remap then unmap for log_sql snippets', () => {+ const result = unmapSqlContentField(remapSqlContentField(LOG_SQL_SNIPPET))++ expect(result.content).toEqual(LOG_SQL_SNIPPET.content)+ })})diff --git a/apps/studio/data/content/content-remap.ts b/apps/studio/data/content/content-remap.tsindex 9d7864da0fd..63141b9bf2b 100644--- a/apps/studio/data/content/content-remap.ts+++ b/apps/studio/data/content/content-remap.ts@@ -1,15 +1,27 @@// Remap `sql` → `unchecked_sql` on SQL snippet content objects as they cross the API boundary.// The API stores and returns the field as `sql`; the frontend type uses `unchecked_sql` to make// it explicit that this value must never be executed without user confirmation.+//+// Both database (`type: 'sql'`) and logs (`type: 'log_sql'`) snippets carry user-authored SQL+// under the same wire field, but each is branded with its own untrusted brand so Postgres SQL+// and logs SQL can never cross execution paths. Branding is per-type and never mixed.import { untrustedSql } from '@supabase/pg-meta'+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'++function isSqlContentType(type: string): type is 'sql' | 'log_sql' {+ return type === 'sql' || type === 'log_sql'+}+export function remapSqlContentField<T extends { type: string }>(item: T): T {- if (item.type !== 'sql') return item+ if (!isSqlContentType(item.type)) return itemif (!('content' in item)) return itemconst content = item.content as Record<string, unknown>if (!('sql' in content)) return itemconst { sql, ...rest } = content- return { ...item, content: { ...rest, unchecked_sql: untrustedSql(sql as string) } } as T+ const unchecked_sql =+ item.type === 'log_sql' ? untrustedLogSql(sql as string) : untrustedSql(sql as string)+ return { ...item, content: { ...rest, unchecked_sql } } as T}export function remapSqlContentFields<T extends { type: string }>(items: Array<T>): Array<T> {@@ -18,10 +30,22 @@ export function remapSqlContentFields<T extends { type: string }>(items: Array<T// Reverse remap: `unchecked_sql` → `sql` before sending to the API.export function unmapSqlContentField<T extends { type: string }>(item: T): T {- if (item.type !== 'sql') return item+ if (!isSqlContentType(item.type)) return itemif (!('content' in item)) return itemconst content = item.content as Record<string, unknown>- if (!('unchecked_sql' in content)) return item+ if (!('unchecked_sql' in content)) {+ // Defensive guard against a writer that still submits the pre-rename `{ sql }` shape.+ // Such a payload happens to reach the wire correctly (the API stores `sql`), but it+ // means a save path was missed during the rename — surface it loudly in development.+ // Crucially, we NEVER fabricate `sql: undefined` here: that would clobber the user's+ // saved query text. The no-op below preserves whatever the content already holds.+ if (process.env.NODE_ENV !== 'production' && 'sql' in content) {+ throw new Error(+ `unmapSqlContentField: ${item.type} content is missing 'unchecked_sql' but still carries a raw 'sql' field — a save path was not migrated to the branded field.`+ )+ }+ return item+ }const { unchecked_sql, ...rest } = contentreturn { ...item, content: { ...rest, sql: unchecked_sql } } as T}diff --git a/apps/studio/data/content/content-upsert-mutation.test.ts b/apps/studio/data/content/content-upsert-mutation.test.tsindex 6c632d57e2c..be1649bd682 100644--- a/apps/studio/data/content/content-upsert-mutation.test.ts+++ b/apps/studio/data/content/content-upsert-mutation.test.ts@@ -3,6 +3,7 @@ import { HttpResponse } from 'msw'import { describe, expect, it } from 'vitest'import { upsertContent } from './content-upsert-mutation'+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'import { addAPIMock } from '@/tests/lib/msw'const SNIPPET_ID = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'@@ -23,6 +24,23 @@ const payload = {},}+const LOGS_SQL =+ "select timestamp, event_message from edge_logs where source = 'edge_logs' limit 10"++const logSqlPayload = {+ id: SNIPPET_ID,+ type: 'log_sql' as const,+ name: 'Saved logs query',+ visibility: 'user' as const,+ project_id: 1,+ owner_id: 1,+ content: {+ content_id: SNIPPET_ID,+ schema_version: '1',+ unchecked_sql: untrustedLogSql(LOGS_SQL),+ },+}+describe('upsertContent', () => {it('remaps content.sql to unchecked_sql in the upsert response', async () => {// Self-hosted (and the management API) persist + return the SQL body under `content.sql`;@@ -61,6 +79,50 @@ describe('upsertContent', () => {expect(result?.content).not.toHaveProperty('sql')})+ it('sends log_sql content as a raw content.sql on the wire and remaps the response back', async () => {+ let sentBody: { type: string; content: Record<string, unknown> } | undefined+ addAPIMock({+ method: 'put',+ path: '/platform/projects/:ref/content',+ response: async ({ request }) => {+ sentBody = (await request.json()) as {+ type: string+ content: Record<string, unknown>+ }+ return HttpResponse.json({+ id: SNIPPET_ID,+ type: 'log_sql',+ name: logSqlPayload.name,+ description: '',+ favorite: false,+ folder_id: null,+ inserted_at: '2024-01-01T00:00:00.000Z',+ updated_at: '2024-01-01T00:00:00.000Z',+ visibility: 'user',+ owner_id: 1,+ project_id: 1,+ content: {+ sql: LOGS_SQL,+ content_id: SNIPPET_ID,+ schema_version: '1',+ },+ })+ },+ })++ const result = await upsertContent({ projectRef: 'default', payload: logSqlPayload })++ // Wire body must carry the plain `sql` field, never the branded `unchecked_sql`.+ expect(sentBody?.type).toBe('log_sql')+ expect(sentBody?.content.sql).toBe(LOGS_SQL)+ expect(sentBody?.content).not.toHaveProperty('unchecked_sql')++ // Response is remapped back to the branded field for the editor.+ expect(result?.status).toBe('saved')+ expect(result?.content?.unchecked_sql).toEqual(untrustedLogSql(LOGS_SQL))+ expect(result?.content).not.toHaveProperty('sql')+ })+it('returns null when the API responds with no snippet', async () => {addAPIMock({method: 'put',diff --git a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx b/apps/studio/pages/project/[ref]/logs/explorer/index.tsxindex e25431adb4a..4d736497fc4 100644--- a/apps/studio/pages/project/[ref]/logs/explorer/index.tsx+++ b/apps/studio/pages/project/[ref]/logs/explorer/index.tsx@@ -40,6 +40,7 @@ import { LogsExplorerOtelBanner } from '@/components/interfaces/Settings/Logs/Loimport { LogsQueryPanel } from '@/components/interfaces/Settings/Logs/LogsQueryPanel'import { LogTable } from '@/components/interfaces/Settings/Logs/LogTable'import UpgradePrompt from '@/components/interfaces/Settings/Logs/UpgradePrompt'+import { useRecentLogSqlSnippets } from '@/components/interfaces/Settings/Logs/useRecentLogSqlSnippets'import { DefaultLayout } from '@/components/layouts/DefaultLayout'import LogsLayout from '@/components/layouts/LogsLayout/LogsLayout'import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'@@ -53,6 +54,7 @@ import {} from '@/data/content/content-upsert-mutation'import { constructHeaders } from '@/data/fetchers'import { fetchOtelLogKeys } from '@/data/logs/otel-log-keys-query'+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'import { useLogsQuery } from '@/hooks/analytics/useLogsQuery'import { useLogsUrlState } from '@/hooks/analytics/useLogsUrlState'import { useCustomContent } from '@/hooks/custom-content/useCustomContent'@@ -150,10 +152,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {false)- const [recentLogs, setRecentLogs] = useLocalStorage<LogSqlSnippets.Content[]>(- `project-content-${projectRef}-recent-log-sql`,- []- )+ const [recentLogs, setRecentLogs] = useRecentLogSqlSnippets(projectRef)const { getEntitlementNumericValue } = useCheckEntitlements('log.retention_days')const entitledToAuditLogDays = getEntitlementNumericValue()@@ -216,7 +215,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {const addRecentLogSqlSnippet = (snippet: Partial<LogSqlSnippets.Content>) => {const defaults: LogSqlSnippets.Content = {schema_version: '1',- sql: '',+ unchecked_sql: untrustedLogSql(''),content_id: '',}setRecentLogs([...recentLogs, { ...defaults, ...snippet }])@@ -241,7 +240,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {editorRef.current.focus()}- addRecentLogSqlSnippet({ sql: template.searchString })+ addRecentLogSqlSnippet({ unchecked_sql: untrustedLogSql(template.searchString) })}const handleRewrite = async () => {@@ -321,7 +320,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {setTimeRange('', '')}setSearch(query)- addRecentLogSqlSnippet({ sql: query })+ addRecentLogSqlSnippet({ unchecked_sql: untrustedLogSql(query) })}const handleInsertSource = (source: string) => {@@ -367,7 +366,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {type: 'log_sql' as const,content: {content_id: editorId,- sql: editorValue,+ unchecked_sql: untrustedLogSql(editorValue),schema_version: '1',favorite: false,} as LogSqlSnippets.Content,@@ -393,7 +392,10 @@ export const LogsExplorerPage: NextPageWithLayout = () => {projectRef: projectRef!,payload: {...query,- content: { ...(query.content as LogSqlSnippets.Content), sql: currentSql },+ content: {+ ...(query.content as LogSqlSnippets.Content),+ unchecked_sql: untrustedLogSql(currentSql),+ },},})@@ -429,7 +431,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {}))}- const querySql = (query?.content as LogSqlSnippets.Content | undefined)?.sql+ const querySql = (query?.content as LogSqlSnippets.Content | undefined)?.unchecked_sqluseEffect(() => {if (search) {setEditorValue(search)diff --git a/apps/studio/pages/project/[ref]/logs/explorer/recent.tsx b/apps/studio/pages/project/[ref]/logs/explorer/recent.tsxindex dd8d11afd9c..a1d26255e0e 100644--- a/apps/studio/pages/project/[ref]/logs/explorer/recent.tsx+++ b/apps/studio/pages/project/[ref]/logs/explorer/recent.tsx@@ -4,20 +4,17 @@ import Link from 'next/link'import { Button } from 'ui'import RecentQueriesItem from '@/components/interfaces/Settings/Logs/RecentQueriesItem'+import { useRecentLogSqlSnippets } from '@/components/interfaces/Settings/Logs/useRecentLogSqlSnippets'import { DefaultLayout } from '@/components/layouts/DefaultLayout'import LogsLayout from '@/components/layouts/LogsLayout/LogsLayout'import Table from '@/components/to-be-cleaned/Table'import LogsExplorerHeader from '@/components/ui/Logs/LogsExplorerHeader'-import { useLocalStorage } from '@/hooks/misc/useLocalStorage'-import type { LogSqlSnippets, NextPageWithLayout } from '@/types'+import type { NextPageWithLayout } from '@/types'export const LogsSavedPage: NextPageWithLayout = () => {const { ref } = useParams()- const [recentLogSnippets, setRecentLogSnippets] = useLocalStorage<LogSqlSnippets.Content[]>(- `project-content-${ref}-recent-log-sql`,- []- )+ const [recentLogSnippets, setRecentLogSnippets] = useRecentLogSqlSnippets(ref)const recent = recentLogSnippets.slice().reverse()return (@@ -35,8 +32,8 @@ export const LogsSavedPage: NextPageWithLayout = () => {</Table.th></>}- body={recent.map((item: LogSqlSnippets.Content) => (- <RecentQueriesItem key={item.sql} item={item} />+ body={recent.map((item) => (+ <RecentQueriesItem key={item.unchecked_sql} item={item} />))}/>)}diff --git a/apps/studio/types/userContent.ts b/apps/studio/types/userContent.tsindex 03f926eeb17..0910808bb82 100644--- a/apps/studio/types/userContent.ts+++ b/apps/studio/types/userContent.ts@@ -1,6 +1,7 @@import type { UntrustedSqlFragment } from '@supabase/pg-meta'import { ChartConfig } from '@/components/interfaces/SQLEditor/UtilityPanel/ChartConfig'+import type { UntrustedLogSqlFragment } from '@/data/logs/safe-analytics-sql'export interface UserContent<T = Dashboards.Content | SqlSnippets.Content | LogSqlSnippets.Content,@@ -123,8 +124,13 @@ export namespace LogSqlSnippets {// unique id of the sql snippet, possibly to used so snippets can support versioningcontent_id: string- // A full SQL query - this will be hashed on the /content endpoint- sql: string+ // A full SQL query - this will be hashed on the /content endpoint.+ // Named unchecked_sql (mirroring SqlSnippets.Content) to highlight that this SQL must+ // never be run automatically without a user run gesture. The API stores/returns it as+ // `sql`; the remap boundary in data/content/content-remap.ts brands it on the way in+ // (untrustedLogSql) and strips the brand on the way out. Distinct from the Postgres+ // brand so logs SQL and database SQL can never cross execution paths.+ unchecked_sql: UntrustedLogSqlFragment// we can add some versioning to this schema in case we need to change the format.schema_version: string