Skip to content

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

feat(studio): discriminated snippet union + source-aware writes (#48313)

Charisfa5eb172778f
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
index 9c6865b0c79..982ef10bb16 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
@@ -16,6 +16,7 @@ import {
checkAlterDatabaseConnection,
checkDestructiveQuery,
computeErrorHighlightLine,
+ createSqlSnippetSkeletonV2,
deriveSnippetIdentity,
extractDebugContext,
filterTablesCoveredByEnsureRLSTrigger,
@@ -433,6 +434,35 @@ describe('SQLEditor.utils.ts:buildCompletionRequestBody', () => {
})
})
+describe('SQLEditor.utils.ts:createSqlSnippetSkeletonV2', () => {
+ const baseArgs = { name: 'Untitled', sql: 'select 1', owner_id: 1, project_id: 1 }
+
+ test('defaults to a database (sql) snippet', () => {
+ const snippet = createSqlSnippetSkeletonV2(baseArgs)
+ expect(snippet.type).toBe('sql')
+ expect(snippet.content?.unchecked_sql).toBe('select 1')
+ expect(snippet.status).toBe('new')
+ })
+
+ test('builds a database snippet when source is explicitly "database"', () => {
+ const snippet = createSqlSnippetSkeletonV2({ ...baseArgs, source: 'database' })
+ expect(snippet.type).toBe('sql')
+ })
+
+ test('builds a logs (log_sql) snippet when source is "logs"', () => {
+ const snippet = createSqlSnippetSkeletonV2({ ...baseArgs, source: 'logs' })
+ expect(snippet.type).toBe('log_sql')
+ expect(snippet.content?.unchecked_sql).toBe('select 1')
+ })
+
+ test('sets content_id to the snippet id for both sources', () => {
+ const db = createSqlSnippetSkeletonV2({ ...baseArgs, idOverride: 'db-id' })
+ const logs = createSqlSnippetSkeletonV2({ ...baseArgs, idOverride: 'logs-id', source: 'logs' })
+ expect(db.content?.content_id).toBe('db-id')
+ expect(logs.content?.content_id).toBe('logs-id')
+ })
+})
+
describe('SQLEditor.utils.ts:planDiffRequestApplication', () => {
test('replaces the editor content when it is empty', () => {
const plan = planDiffRequestApplication({
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
index 2c47067791b..de83b8a48e5 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
@@ -7,6 +7,7 @@ import {
} from '@supabase/pg-meta'
import { TABLE_EVENT_ACTIONS } from 'common/telemetry-constants'
+import type { SqlSnippetSource } from './querySource'
import {
alterDatabasePreventConnectionStatements,
destructiveSqlRegex,
@@ -23,6 +24,7 @@ import {
} from './SQLEditor.types'
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
import type { DatabaseEventTrigger } from '@/data/database-event-triggers/database-event-triggers-query'
+import { untrustedLogSql, type UntrustedLogSqlFragment } from '@/data/logs/safe-analytics-sql'
import type { Database } from '@/data/read-replicas/replicas-query'
import { generateUuid } from '@/lib/api/snippets.browser'
import { removeCommentsFromSql } from '@/lib/helpers'
@@ -72,6 +74,7 @@ export const createSqlSnippetSkeletonV2 = ({
project_id,
folder_id,
idOverride,
+ source = 'database',
}: {
name: string
sql: string
@@ -83,10 +86,14 @@ export const createSqlSnippetSkeletonV2 = ({
* with a known id, such as to prevent flicker in the SQL editor when adding new unsaved snippets.
*/
idOverride?: string
+ /**
+ * Which backend the new snippet targets.
+ */
+ source?: SqlSnippetSource
}): SnippetWithContent => {
const id = idOverride ?? generateUuid([folder_id, `${name}.sql`])
- return {
+ const base = {
...NEW_SQL_SNIPPET_SKELETON,
id,
owner_id,
@@ -96,12 +103,29 @@ export const createSqlSnippetSkeletonV2 = ({
favorite: false,
inserted_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
+ status: 'new' as const,
+ }
+
+ if (source === 'logs') {
+ return {
+ ...base,
+ type: 'log_sql',
+ content: {
+ schema_version: NEW_SQL_SNIPPET_SKELETON.content.schema_version,
+ content_id: id ?? '',
+ unchecked_sql: untrustedLogSql(sql ?? ''),
+ },
+ }
+ }
+
+ return {
+ ...base,
+ type: 'sql',
content: {
...NEW_SQL_SNIPPET_SKELETON.content,
content_id: id ?? '',
unchecked_sql: untrustedSql(sql ?? ''),
- } as any,
- status: 'new',
+ },
}
}
@@ -511,7 +535,11 @@ export function buildDebugPromptText(sql: string, errorMessage: string): string
return `${prompt}\n\nSQL Query:\n\`\`\`sql\n${sql}\n\`\`\``
}
-type DebugSnippet = { snippet: { content?: { unchecked_sql?: UntrustedSqlFragment } } } | undefined
+// Accepts either brand: the debug flow only reads the SQL as text (it's stripped
+// and interpolated into a prompt), so a logs-branded fragment is fine here.
+type DebugSnippet =
+ | { snippet: { content?: { unchecked_sql?: UntrustedSqlFragment | UntrustedLogSqlFragment } } }
+ | undefined
type DebugResult = { error?: { message?: string } } | undefined
/**
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
index 03aeffa3f24..26fdb923206 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
@@ -147,8 +147,9 @@ export const SQLEditorControllersProvider = ({ children }: PropsWithChildren) =>
// Reads the SQL to run from the editor as an UntrustedSqlFragment. Promotion
// to safety (acceptUntrustedSql) happens at each user-action site, never here.
const readEditorSql = useCallback((): UntrustedSqlFragment | undefined => {
- const snippet = getSqlEditorV2StateSnapshot().snippets[id]
- return editor.getSql(snippet?.snippet.content?.unchecked_sql)
+ const snippet = getSqlEditorV2StateSnapshot().snippets[id]?.snippet
+ const fallback = snippet?.type === 'log_sql' ? undefined : snippet?.content?.unchecked_sql
+ return editor.getSql(fallback)
}, [editor, id])
const { executeQuery, isExecuting, potentialIssues, resetPotentialIssues } =
diff --git a/apps/studio/components/interfaces/SQLEditor/querySource.test.ts b/apps/studio/components/interfaces/SQLEditor/querySource.test.ts
new file mode 100644
index 00000000000..16f1e6ae16d
--- /dev/null
+++ b/apps/studio/components/interfaces/SQLEditor/querySource.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest'
+
+import { getSnippetSource } from './querySource'
+
+describe('querySource.ts:getSnippetSource', () => {
+ it('maps log_sql to the logs source', () => {
+ expect(getSnippetSource({ type: 'log_sql' })).toBe('logs')
+ })
+
+ it('maps sql to the database source', () => {
+ expect(getSnippetSource({ type: 'sql' })).toBe('database')
+ })
+
+ it('maps report to the database source', () => {
+ expect(getSnippetSource({ type: 'report' })).toBe('database')
+ })
+})
diff --git a/apps/studio/components/interfaces/SQLEditor/querySource.ts b/apps/studio/components/interfaces/SQLEditor/querySource.ts
new file mode 100644
index 00000000000..ed6bf4e6412
--- /dev/null
+++ b/apps/studio/components/interfaces/SQLEditor/querySource.ts
@@ -0,0 +1,20 @@
+import type { Snippet } from '@/data/content/sql-folders-query'
+
+/**
+ * Domain view of where a snippet's query runs. Derived from the content TYPE:
+ * a `log_sql` snippet always targets the logs backend and a `sql` (or `report`)
+ * snippet always targets the user's Postgres database. A snippet's source is
+ * immutable — switching backends means creating a new snippet, not toggling this
+ * value.
+ */
+export type SqlSnippetSource = 'database' | 'logs'
+
+/**
+ * The single reader every surface (AI, reports, tabs, nav, execution) uses to
+ * decide where a snippet runs. `'log_sql'` → `'logs'`; everything else (`'sql'`,
+ * `'report'`) → `'database'`. Accepts the raw `Snippet['type']` so a snippet of
+ * any content type maps to a source without narrowing first.
+ */
+export function getSnippetSource(snippet: Pick<Snippet, 'type'>): SqlSnippetSource {
+ return snippet.type === 'log_sql' ? 'logs' : 'database'
+}
diff --git a/apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts b/apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts
index 60c415e79d3..9a70c333034 100644
--- a/apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts
+++ b/apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts
@@ -25,7 +25,9 @@ export function usePrettifyQuery({ id, isDiffOpen }: { id: string; isDiffOpen: b
const snippet = state.snippets[id]
if (editor.isReady() && project) {
- const sql = editor.getSql(snippet?.snippet.content?.unchecked_sql)
+ const fallback =
+ snippet?.snippet.type === 'log_sql' ? undefined : snippet?.snippet.content?.unchecked_sql
+ const sql = editor.getSql(fallback)
if (sql === undefined) return
const formattedSql = formatSql(sql)
diff --git a/apps/studio/data/content/content-id-query.ts b/apps/studio/data/content/content-id-query.ts
index 681e7c645ca..37547ab58fe 100644
--- a/apps/studio/data/content/content-id-query.ts
+++ b/apps/studio/data/content/content-id-query.ts
@@ -2,7 +2,7 @@ import { useQuery } from '@tanstack/react-query'
import { components } from 'api-types'
import type { Content } from './content-query'
-import { remapSqlContentField } from './content-remap'
+import { remapSqlContentField, remapWireSnippet } from './content-remap'
import { contentKeys } from './keys'
import type { SnippetWithContent } from './sql-folders-query'
import { get, handleError } from '@/data/fetchers'
@@ -51,8 +51,7 @@ export async function getSqlSnippetById(
})
if (error) throw handleError(error)
- const snippet = remapSqlContentField(data as unknown as Omit<SnippetWithContent, 'status'>)
- return { ...snippet, status: 'saved' }
+ return remapWireSnippet(data, 'saved')
}
export type SqlSnippetByIdData = Awaited<ReturnType<typeof getSqlSnippetById>>
diff --git a/apps/studio/data/content/content-remap.ts b/apps/studio/data/content/content-remap.ts
index 63141b9bf2b..e3f4b397ef1 100644
--- a/apps/studio/data/content/content-remap.ts
+++ b/apps/studio/data/content/content-remap.ts
@@ -7,6 +7,8 @@
// and logs SQL can never cross execution paths. Branding is per-type and never mixed.
import { untrustedSql } from '@supabase/pg-meta'
+import type { SnippetStatus } from './snippet-status'
+import type { SnippetWithContent } from './sql-folders-query'
import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
function isSqlContentType(type: string): type is 'sql' | 'log_sql' {
@@ -28,6 +30,17 @@ export function remapSqlContentFields<T extends { type: string }>(items: Array<T
return items.map(remapSqlContentField)
}
+// Wire→domain boundary for a single SQL-editor snippet. The platform API types a
+// content row's `content` as an opaque `{ [key: string]: unknown }` map (and its
+// `type` as the full `'sql' | 'report' | 'log_sql'`), so turning a fetched row
+// into a branded, discriminated `SnippetWithContent` needs exactly one assertion.
+// Concentrating it here — the single place that already owns the sql↔unchecked_sql
+// rename — keeps the query/mutation call sites free of `as unknown as` casts.
+export function remapWireSnippet(row: unknown, status: SnippetStatus): SnippetWithContent {
+ const snippet = remapSqlContentField(row as SnippetWithContent)
+ return { ...snippet, status }
+}
+
// Reverse remap: `unchecked_sql` → `sql` before sending to the API.
export function unmapSqlContentField<T extends { type: string }>(item: T): T {
if (!isSqlContentType(item.type)) return item
diff --git a/apps/studio/data/content/content-upsert-mutation.ts b/apps/studio/data/content/content-upsert-mutation.ts
index 26640dbb066..8ce336b7684 100644
--- a/apps/studio/data/content/content-upsert-mutation.ts
+++ b/apps/studio/data/content/content-upsert-mutation.ts
@@ -2,9 +2,9 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import type { Content } from './content-query'
-import { remapSqlContentField, unmapSqlContentField } from './content-remap'
+import { remapWireSnippet, unmapSqlContentField } from './content-remap'
import { contentKeys } from './keys'
-import type { Snippet, SnippetWithContent } from './sql-folders-query'
+import type { SnippetWithContent } from './sql-folders-query'
import type { components } from '@/data/api'
import { handleError, put } from '@/data/fetchers'
import type { ResponseError, UseCustomMutationOptions } from '@/types'
@@ -31,9 +31,9 @@ export async function upsertContent(
signal,
})
if (error) handleError(error)
+ if (!data) return null
- const snippet = data as Snippet | null
- return snippet === null ? null : { ...remapSqlContentField(snippet), status: 'saved' }
+ return remapWireSnippet(data, 'saved')
}
export type UpsertContentData = Awaited<ReturnType<typeof upsertContent>>
diff --git a/apps/studio/data/content/sql-folders-query.ts b/apps/studio/data/content/sql-folders-query.ts
index 36d31c6a505..85d2ec4b5b1 100644
--- a/apps/studio/data/content/sql-folders-query.ts
+++ b/apps/studio/data/content/sql-folders-query.ts
@@ -4,7 +4,12 @@ import { components } from 'api-types'
import { contentKeys } from './keys'
import type { SnippetStatus } from './snippet-status'
import { get, handleError } from '@/data/fetchers'
-import type { ResponseError, SqlSnippets, UseCustomInfiniteQueryOptions } from '@/types'
+import type {
+ LogSqlSnippets,
+ ResponseError,
+ SqlSnippets,
+ UseCustomInfiniteQueryOptions,
+} from '@/types'
export type SnippetFolderResponse = components['schemas']['GetUserContentFolderResponse']['data']
export type SnippetFolder =
@@ -12,10 +17,25 @@ export type SnippetFolder =
export type Snippet =
components['schemas']['GetUserContentFolderResponse']['data']['contents'][number]
-export interface SnippetWithContent extends Snippet {
- content?: SqlSnippets.Content
- status: SnippetStatus
-}
+// The SQL editor's loaded-snippet type. Discriminated on `type` so database SQL
+// (`SqlSnippets.Content`, Postgres brand) and logs SQL (`LogSqlSnippets.Content`,
+// logs brand) can never cross execution paths: reading `snippet.content.unchecked_sql`
+// on the union yields the widened brand, forcing callers that need one specific
+// brand to narrow on `type` first. The shared field names (`content_id`,
+// `unchecked_sql`, `schema_version`) keep the many read sites that only need the
+// SQL text compiling unchanged.
+//
+// `report` is included because the content endpoints' wire type carries it, but
+// it deliberately has NO SQL content (`content?: never`): report bodies are
+// `Dashboards.Content` and are loaded through the separate `Content` union
+// (data/content/content-query.ts), never with SQL here. Modelling it as `never`
+// (rather than reusing `SqlSnippets.Content`) keeps that honest while letting the
+// broadly-typed rows the content/folder queries return assign without a cast.
+export type SnippetWithContent = Omit<Snippet, 'type'> & { status: SnippetStatus } & (
+ | { type: 'sql'; content?: SqlSnippets.Content }
+ | { type: 'log_sql'; content?: LogSqlSnippets.Content }
+ | { type: 'report'; content?: never }
+ )
// Attaches the 'saved' lifecycle status to a snippet as it crosses from the
// database into the app. Generic so it preserves any loaded content on the
diff --git a/apps/studio/data/content/sql-snippets-query.ts b/apps/studio/data/content/sql-snippets-query.ts
index afd112f9535..ef4aac6673c 100644
--- a/apps/studio/data/content/sql-snippets-query.ts
+++ b/apps/studio/data/content/sql-snippets-query.ts
@@ -3,9 +3,9 @@ import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query'
import { Content } from './content-query'
import { remapSqlContentFields } from './content-remap'
import { contentKeys } from './keys'
-import { SNIPPET_PAGE_LIMIT, withSavedStatus, type Snippet } from './sql-folders-query'
+import { SNIPPET_PAGE_LIMIT, withSavedStatus, type SnippetWithContent } from './sql-folders-query'
import { get } from '@/data/fetchers'
-import type { SqlSnippets, UseCustomInfiniteQueryOptions } from '@/types'
+import type { UseCustomInfiniteQueryOptions } from '@/types'
export type SqlSnippet = Extract<Content, { type: 'sql' }>
@@ -49,9 +49,7 @@ export async function getSqlSnippets(
throw error
}
- const snippets = remapSqlContentFields(
- data.data as unknown as Array<Snippet & { content?: SqlSnippets.Content }>
- )
+ const snippets = remapSqlContentFields(data.data as unknown as SnippetWithContent[])
return {
cursor: data.cursor,
contents: snippets.map(withSavedStatus),
diff --git a/apps/studio/state/sql-editor/sql-editor-rules.test.ts b/apps/studio/state/sql-editor/sql-editor-rules.test.ts
index 0f8ec256e6a..a46f443f61d 100644
--- a/apps/studio/state/sql-editor/sql-editor-rules.test.ts
+++ b/apps/studio/state/sql-editor/sql-editor-rules.test.ts
@@ -10,11 +10,35 @@ import {
type LoadedSnippet,
} from './sql-editor-rules'
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
-function makeSnippet(overrides: Omit<Partial<SnippetWithContent>, 'content'> = {}): LoadedSnippet {
+function makeLogSnippet(): LoadedSnippet {
+ return {
+ id: 'log-snippet-1',
+ name: 'My Logs Query',
+ description: '',
+ visibility: 'user',
+ project_id: 42,
+ owner_id: 7,
+ folder_id: null,
+ favorite: false,
+ status: 'saved',
+ inserted_at: '2024-01-01T00:00:00.000Z',
+ updated_at: '2024-01-01T00:00:00.000Z',
+ type: 'log_sql',
+ content: {
+ content_id: 'log-snippet-1',
+ schema_version: '1',
+ unchecked_sql: untrustedLogSql('select * from logs'),
+ },
+ }
+}
+
+function makeSnippet(
+ overrides: Omit<Partial<SnippetWithContent>, 'content' | 'type'> = {}
+): LoadedSnippet {
return {
id: 'snippet-1',
- type: 'sql',
name: 'My Query',
description: 'A description',
visibility: 'user',
@@ -26,6 +50,7 @@ function makeSnippet(overrides: Omit<Partial<SnippetWithContent>, 'content'> = {
inserted_at: '2024-01-01T00:00:00.000Z',
updated_at: '2024-01-01T00:00:00.000Z',
...overrides,
+ type: 'sql',
content: {
content_id: 'snippet-1',
schema_version: '1',
@@ -96,6 +121,17 @@ describe('validateMoveToFolder', () => {
})
describe('buildUpsertPayload', () => {
+ it('emits the snippet type — sql for a database snippet', () => {
+ const payload = buildUpsertPayload(makeSnippet(), 'snippet-1')
+ expect(payload.type).toBe('sql')
+ })
+
+ it('emits the snippet type — log_sql for a logs snippet (not silently rewritten to sql)', () => {
+ const payload = buildUpsertPayload(makeLogSnippet(), 'log-snippet-1')
+ expect(payload.type).toBe('log_sql')
+ expect((payload.content as { content_id: string }).content_id).toBe('log-snippet-1')
+ })
+
it('passes through provided values', () => {
const snippet = makeSnippet()
const payload = buildUpsertPayload(snippet, 'snippet-1')
diff --git a/apps/studio/state/sql-editor/sql-editor-rules.ts b/apps/studio/state/sql-editor/sql-editor-rules.ts
index b1c52682d28..2702e251b5d 100644
--- a/apps/studio/state/sql-editor/sql-editor-rules.ts
+++ b/apps/studio/state/sql-editor/sql-editor-rules.ts
@@ -51,7 +51,7 @@ export function buildUpsertPayload(snippet: LoadedSnippet, id: string): UpsertCo
snippet
return {
id,
- type: 'sql',
+ type: snippet.type,
name: name ?? 'Untitled',
description: description ?? '',
visibility: visibility ?? 'user',
diff --git a/apps/studio/state/sql-editor/sql-editor-save-scheduler.test.ts b/apps/studio/state/sql-editor/sql-editor-save-scheduler.test.ts
index 00dc272a804..ba39dbda6d4 100644
--- a/apps/studio/state/sql-editor/sql-editor-save-scheduler.test.ts
+++ b/apps/studio/state/sql-editor/sql-editor-save-scheduler.test.ts
@@ -5,11 +5,16 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { createSaveScheduler, type SaveMode } from './sql-editor-save-scheduler'
import type { StateSnippet, StateSnippetFolder } from './types'
+import type { SqlSnippets } from '@/types'
// Valtio notifies subscribers on a microtask; flush past it before asserting.
const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0))
-function makeStateSnippet(overrides: Partial<StateSnippet['snippet']> = {}): StateSnippet {
+function makeStateSnippet(
+ overrides: Omit<Partial<StateSnippet['snippet']>, 'type' | 'content'> & {
+ content?: SqlSnippets.Content
+ } = {}
+): StateSnippet {
return {
projectRef: 'ref',
splitSizes: [50, 50],
diff --git a/apps/studio/state/sql-editor/sql-editor-save.test.ts b/apps/studio/state/sql-editor/sql-editor-save.test.ts
index 506dbfcc7ed..30f5a6da77f 100644
--- a/apps/studio/state/sql-editor/sql-editor-save.test.ts
+++ b/apps/studio/state/sql-editor/sql-editor-save.test.ts
@@ -4,8 +4,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createSaveMechanism, type SaveMechanismStore } from './sql-editor-save'
import type { StateSnippet } from './types'
import type { SnippetFolder } from '@/data/content/sql-folders-query'
+import type { SqlSnippets } from '@/types'
-function makeStateSnippet(overrides: Partial<StateSnippet['snippet']> = {}): StateSnippet {
+function makeStateSnippet(
+ overrides: Omit<Partial<StateSnippet['snippet']>, 'type' | 'content'> & {
+ content?: SqlSnippets.Content
+ } = {}
+): StateSnippet {
return {
projectRef: 'ref',
splitSizes: [50, 50],
diff --git a/apps/studio/state/sql-editor/sql-editor-state.test.ts b/apps/studio/state/sql-editor/sql-editor-state.test.ts
index ba59013f006..3bceae2105a 100644
--- a/apps/studio/state/sql-editor/sql-editor-state.test.ts
+++ b/apps/studio/state/sql-editor/sql-editor-state.test.ts
@@ -3,14 +3,36 @@ import { beforeEach, describe, expect, it } from 'vitest'
import { sqlEditorState } from './sql-editor-state'
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
+
+function makeLogSnippet(id: string): SnippetWithContent {
+ return {
+ id,
+ name: 'My Logs Query',
+ description: '',
+ visibility: 'user',
+ project_id: 42,
+ owner_id: 7,
+ folder_id: null,
+ favorite: false,
+ status: 'saved',
+ inserted_at: '2024-01-01T00:00:00.000Z',
+ updated_at: '2024-01-01T00:00:00.000Z',
+ type: 'log_sql',
+ content: {
+ content_id: id,
+ schema_version: '1',
+ unchecked_sql: untrustedLogSql('select * from logs'),
+ },
+ }
+}
function makeSnippet(
id: string,
- overrides: Omit<Partial<SnippetWithContent>, 'content'> = {}
+ overrides: Omit<Partial<SnippetWithContent>, 'content' | 'type'> = {}
): SnippetWithContent {
return {
id,
- type: 'sql',
name: 'My Query',
description: 'A description',
visibility: 'user',
@@ -22,6 +44,7 @@ function makeSnippet(
inserted_at: '2024-01-01T00:00:00.000Z',
updated_at: '2024-01-01T00:00:00.000Z',
...overrides,
+ type: 'sql',
content: {
content_id: id,
schema_version: '1',
@@ -70,3 +93,32 @@ describe('addFavorite / removeFavorite', () => {
expect(sqlEditorState.needsSaving.has('missing')).toBe(false)
})
})
+
+describe('setSql — source-aware branding', () => {
+ beforeEach(() => {
+ for (const id of Object.keys(sqlEditorState.snippets)) {
+ delete sqlEditorState.snippets[id]
+ }
+ sqlEditorState.needsSaving.clear()
+ })
+
+ it('updates the SQL of a database snippet and marks it for saving', () => {
+ sqlEditorState.addSnippet({ projectRef: 'ref', snippet: makeSnippet('db-1') })
+
+ sqlEditorState.setSql({ id: 'db-1', sql: 'select 2' })
+
+ expect(sqlEditorState.snippets['db-1'].snippet.content?.unchecked_sql).toBe('select 2')
+ expect(sqlEditorState.needsSaving.has('db-1')).toBe(true)
+ })
+
+ it('updates the SQL of a logs snippet and marks it for saving', () => {
+ sqlEditorState.addSnippet({ projectRef: 'ref', snippet: makeLogSnippet('logs-1') })
+
+ sqlEditorState.setSql({ id: 'logs-1', sql: 'select count(*) from logs' })
+
+ expect(sqlEditorState.snippets['logs-1'].snippet.content?.unchecked_sql).toBe(
+ 'select count(*) from logs'
+ )
+ expect(sqlEditorState.needsSaving.has('logs-1')).toBe(true)
+ })
+})
diff --git a/apps/studio/state/sql-editor/sql-editor-state.ts b/apps/studio/state/sql-editor/sql-editor-state.ts
index c0073c6df9f..c3519a75ea8 100644
--- a/apps/studio/state/sql-editor/sql-editor-state.ts
+++ b/apps/studio/state/sql-editor/sql-editor-state.ts
@@ -14,6 +14,7 @@ import { sqlEditorSessionState } from './sql-editor-session-state'
import type { StateSnippet, StateSnippetFolder } from './types'
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
import { Snippet, SnippetFolder } from '@/data/content/sql-folders-query'
+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
export const sqlEditorState = proxy({
// ========================================================================
@@ -84,7 +85,7 @@ export const sqlEditorState = proxy({
skipSave = false,
}: {
id: string
- snippet: Partial<Snippet>
+ snippet: Omit<Partial<Snippet>, 'type'>
skipSave?: boolean
}) => {
if (sqlEditorState.snippets[id]) {
@@ -127,7 +128,11 @@ export const sqlEditorState = proxy({
}) => {
let snippet = sqlEditorState.snippets[id]?.snippet
if (snippet?.content) {
- snippet.content.unchecked_sql = untrustedSql(sql)
+ if (snippet.type === 'log_sql') {
+ snippet.content.unchecked_sql = untrustedLogSql(sql)
+ } else {
+ snippet.content.unchecked_sql = untrustedSql(sql)
+ }
// Mark dirty immediately so `status` (not the transient needsSaving queue)
// is the durable source of truth for unsaved changes, even before the
// debounced save begins.
diff --git a/apps/studio/tests/lib/sql-editor-test-utils.tsx b/apps/studio/tests/lib/sql-editor-test-utils.tsx
index 3be4957d80b..0f4a6cf855e 100644
--- a/apps/studio/tests/lib/sql-editor-test-utils.tsx
+++ b/apps/studio/tests/lib/sql-editor-test-utils.tsx
@@ -5,6 +5,7 @@ import { http, HttpResponse } from 'msw'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import type { ReactNode } from 'react'
+import type { SqlSnippetSource } from '@/components/interfaces/SQLEditor/querySource'
import type {
ContentDiff,
DiffController,
@@ -147,6 +148,7 @@ export function seedSnippet({
sql = '',
ownerId = 1,
projectId = 1,
+ source = 'database',
}: {
id: string
projectRef?: string
@@ -154,6 +156,7 @@ export function seedSnippet({
sql?: string
ownerId?: number
projectId?: number
+ source?: SqlSnippetSource
}) {
const snippet = createSqlSnippetSkeletonV2({
name,
@@ -161,6 +164,7 @@ export function seedSnippet({
owner_id: ownerId,
project_id: projectId,
idOverride: id,
+ source,
})
sqlEditorState.addSnippet({ projectRef, snippet })
return snippet