Skip to content

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

refactor(studio): extract SQL editor domain rules into pure module (2/9) (#47204)

Charise1e2498db092
diff --git a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
index 70b246d9847..dc954c5088a 100644
--- a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
@@ -19,6 +19,7 @@ import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useIsShortcutEnabled } from '@/state/shortcuts/useIsShortcutEnabled'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { canEditSnippet } from '@/state/sql-editor/sql-editor-rules'
import { useTabsStateSnapshot } from '@/state/tabs'
export type MonacoEditorProps = {
@@ -79,8 +80,7 @@ export const MonacoEditor = ({
const debouncedValue = useDebounce(value, 1000)
const snippet = snapV2.snippets[id]
- const disableEdit =
- snippet?.snippet.visibility === 'project' && snippet?.snippet.owner_id !== profile?.id
+ const disableEdit = !!snippet && !canEditSnippet(snippet.snippet, profile?.id)
const executeExplainQueryRef = useRef(executeExplainQuery)
executeExplainQueryRef.current = executeExplainQuery
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ReadOnlyBadge.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ReadOnlyBadge.tsx
index 7a2a8aa75d0..253675db650 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ReadOnlyBadge.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ReadOnlyBadge.tsx
@@ -2,6 +2,7 @@ import { Badge } from 'ui'
import { useProfile } from '@/lib/profile'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { isSnippetOwner } from '@/state/sql-editor/sql-editor-rules'
export type ReadOnlyBadgeProps = { id: string }
const ReadOnlyBadge = ({ id }: ReadOnlyBadgeProps) => {
@@ -9,9 +10,9 @@ const ReadOnlyBadge = ({ id }: ReadOnlyBadgeProps) => {
const snapV2 = useSqlEditorV2StateSnapshot()
const snippet = snapV2.snippets[id]
- const isSnippetOwner = profile?.id === snippet?.snippet.owner_id
+ const snippetIsOwned = !!snippet && isSnippetOwner(snippet.snippet, profile?.id)
- return <>{isSnippetOwner ? null : <Badge>Read-only</Badge>}</>
+ return <>{snippetIsOwned ? null : <Badge>Read-only</Badge>}</>
}
export default ReadOnlyBadge
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/SavingIndicator.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/SavingIndicator.tsx
index 26f92e1b712..12c34a4214d 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/SavingIndicator.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/SavingIndicator.tsx
@@ -6,6 +6,7 @@ import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import ReadOnlyBadge from './ReadOnlyBadge'
import { useProfile } from '@/lib/profile'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { isSnippetOwner } from '@/state/sql-editor/sql-editor-rules'
export type SavingIndicatorProps = { id: string }
@@ -18,7 +19,7 @@ const SavingIndicator = ({ id }: SavingIndicatorProps) => {
const [showSavedText, setShowSavedText] = useState(false)
const snippet = snapV2.snippets[id]
- const isSnippetOwner = profile?.id === snippet?.snippet.owner_id
+ const snippetIsOwned = !!snippet && isSnippetOwner(snippet.snippet, profile?.id)
useEffect(() => {
let cancel = false
@@ -40,7 +41,7 @@ const SavingIndicator = ({ id }: SavingIndicatorProps) => {
return (
<>
<div className="mx-2 flex items-center gap-2">
- {isSnippetOwner && savingState === 'UPDATING_FAILED' && (
+ {snippetIsOwned && savingState === 'UPDATING_FAILED' && (
<Button
variant="text"
size="tiny"
@@ -65,7 +66,7 @@ const SavingIndicator = ({ id }: SavingIndicatorProps) => {
<TooltipContent>Saving changes...</TooltipContent>
</Tooltip>
) : savingState === 'UPDATING_FAILED' ? (
- isSnippetOwner ? (
+ snippetIsOwned ? (
<Tooltip>
<TooltipTrigger>
<AlertCircle className="text-red-900" size={14} strokeWidth={2} />
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx
index 8977c1cbf41..2235f37d60e 100644
--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx
+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx
@@ -177,12 +177,27 @@ export const SQLEditorTreeViewItem = ({
}
}
- const onToggleFavorite = () => {
+ const onToggleFavorite = async () => {
const snippetId = element.metadata.id
- if (snippetId) {
- if (isFavorite) snapV2.removeFavorite(snippetId)
- else snapV2.addFavorite(snippetId)
+ if (!snippetId) return
+ if (!projectRef) return console.error('Project ref is required')
+
+ // Persisting a favorite goes through the full content upsert, so the
+ // snippet's content must be loaded first — otherwise the PUT endpoint
+ // rejects the update. Snippets listed in the nav that have never been
+ // opened have no content loaded yet, so fetch it before toggling.
+ const storeSnippet = snapV2.snippets[snippetId]
+ if (!storeSnippet?.snippet.content) {
+ const data = await getContentById({ projectRef, id: snippetId })
+ // getContentById returns a union content; narrow to the SQL variant (the
+ // only kind the SQL editor loads) via its discriminating field.
+ if ('unchecked_sql' in data.content) {
+ snapV2.setSnippet(projectRef, { ...data, content: data.content })
+ }
}
+
+ if (isFavorite) snapV2.removeFavorite(snippetId)
+ else snapV2.addFavorite(snippetId)
}
const onSelectDuplicate = async () => {
diff --git a/apps/studio/state/sql-editor/sql-editor-rules.test.ts b/apps/studio/state/sql-editor/sql-editor-rules.test.ts
new file mode 100644
index 00000000000..ae72393f1b0
--- /dev/null
+++ b/apps/studio/state/sql-editor/sql-editor-rules.test.ts
@@ -0,0 +1,181 @@
+import { untrustedSql } from '@supabase/pg-meta'
+import { describe, expect, it } from 'vitest'
+
+import {
+ buildUpsertPayload,
+ canEditSnippet,
+ isLoadedSnippet,
+ isSnippetOwner,
+ validateMoveToFolder,
+ type LoadedSnippet,
+} from './sql-editor-rules'
+import type { SnippetWithContent } from './types'
+
+function makeSnippet(overrides: Omit<Partial<SnippetWithContent>, 'content'> = {}): LoadedSnippet {
+ return {
+ id: 'snippet-1',
+ type: 'sql',
+ name: 'My Query',
+ description: 'A description',
+ visibility: 'user',
+ project_id: 42,
+ owner_id: 7,
+ folder_id: null,
+ favorite: false,
+ inserted_at: '2024-01-01T00:00:00.000Z',
+ updated_at: '2024-01-01T00:00:00.000Z',
+ ...overrides,
+ content: {
+ content_id: 'snippet-1',
+ schema_version: '1',
+ unchecked_sql: untrustedSql('SELECT * FROM users;'),
+ },
+ }
+}
+
+describe('canEditSnippet', () => {
+ it('returns true for owner of a project-visibility snippet', () => {
+ const snippet = makeSnippet({ visibility: 'project', owner_id: 7 })
+ expect(canEditSnippet(snippet, 7)).toBe(true)
+ })
+
+ it('returns false for non-owner of a project-visibility snippet', () => {
+ const snippet = makeSnippet({ visibility: 'project', owner_id: 7 })
+ expect(canEditSnippet(snippet, 99)).toBe(false)
+ })
+
+ it('returns true for non-owner of a user-visibility snippet', () => {
+ const snippet = makeSnippet({ visibility: 'user', owner_id: 7 })
+ expect(canEditSnippet(snippet, 99)).toBe(true)
+ })
+
+ it('returns false when profileId is undefined and snippet is project-visibility', () => {
+ const snippet = makeSnippet({ visibility: 'project', owner_id: 7 })
+ expect(canEditSnippet(snippet, undefined)).toBe(false)
+ })
+})
+
+describe('isSnippetOwner', () => {
+ it('returns true when profileId matches owner_id', () => {
+ const snippet = makeSnippet({ owner_id: 7 })
+ expect(isSnippetOwner(snippet, 7)).toBe(true)
+ })
+
+ it('returns false when profileId does not match owner_id', () => {
+ const snippet = makeSnippet({ owner_id: 7 })
+ expect(isSnippetOwner(snippet, 99)).toBe(false)
+ })
+
+ it('returns false when profileId is undefined', () => {
+ const snippet = makeSnippet({ owner_id: 7 })
+ expect(isSnippetOwner(snippet, undefined)).toBe(false)
+ })
+})
+
+describe('validateMoveToFolder', () => {
+ it('returns { ok: false } when visibility is project and folderId is set', () => {
+ const result = validateMoveToFolder({ visibility: 'project', folderId: 'folder-abc' })
+ expect(result).toEqual({ ok: false, error: 'Shared snippet cannot be within a folder' })
+ })
+
+ it('returns { ok: true } when visibility is project and folderId is null', () => {
+ const result = validateMoveToFolder({ visibility: 'project', folderId: null })
+ expect(result).toEqual({ ok: true })
+ })
+
+ it('returns { ok: true } when visibility is project and folderId is undefined', () => {
+ const result = validateMoveToFolder({ visibility: 'project', folderId: undefined })
+ expect(result).toEqual({ ok: true })
+ })
+
+ it('returns { ok: true } when visibility is user and folderId is set', () => {
+ const result = validateMoveToFolder({ visibility: 'user', folderId: 'folder-abc' })
+ expect(result).toEqual({ ok: true })
+ })
+})
+
+describe('buildUpsertPayload', () => {
+ it('passes through provided values', () => {
+ const snippet = makeSnippet()
+ const payload = buildUpsertPayload(snippet, 'snippet-1')
+
+ expect(payload.id).toBe('snippet-1')
+ expect(payload.type).toBe('sql')
+ expect(payload.name).toBe('My Query')
+ expect(payload.description).toBe('A description')
+ expect(payload.visibility).toBe('user')
+ expect(payload.project_id).toBe(42)
+ expect(payload.owner_id).toBe(7)
+ expect(payload.favorite).toBe(false)
+ })
+
+ it('applies Untitled default when name is undefined', () => {
+ const snippet = makeSnippet({ name: undefined })
+ const payload = buildUpsertPayload(snippet, 'snippet-1')
+ expect(payload.name).toBe('Untitled')
+ })
+
+ it('applies empty-string default when description is undefined', () => {
+ const snippet = makeSnippet({ description: undefined })
+ const payload = buildUpsertPayload(snippet, 'snippet-1')
+ expect(payload.description).toBe('')
+ })
+
+ it('applies user default when visibility is undefined', () => {
+ const snippet = makeSnippet({ visibility: undefined })
+ const payload = buildUpsertPayload(snippet, 'snippet-1')
+ expect(payload.visibility).toBe('user')
+ })
+
+ it('applies 0 default when project_id is undefined', () => {
+ const snippet = makeSnippet({ project_id: undefined })
+ const payload = buildUpsertPayload(snippet, 'snippet-1')
+ expect(payload.project_id).toBe(0)
+ })
+
+ it('applies false default when favorite is undefined', () => {
+ const snippet = makeSnippet({ favorite: undefined })
+ const payload = buildUpsertPayload(snippet, 'snippet-1')
+ expect(payload.favorite).toBe(false)
+ })
+
+ it('sets content.content_id to the supplied id', () => {
+ const snippet = makeSnippet()
+ const payload = buildUpsertPayload(snippet, 'my-id')
+ expect((payload.content as any).content_id).toBe('my-id')
+ })
+
+ it('converts folder_id null to undefined in the payload', () => {
+ const snippet = makeSnippet({ folder_id: null })
+ const payload = buildUpsertPayload(snippet, 'snippet-1')
+ expect(payload.folder_id).toBeUndefined()
+ })
+
+ it('passes through a non-null folder_id', () => {
+ const snippet = makeSnippet({ folder_id: 'folder-xyz' })
+ const payload = buildUpsertPayload(snippet, 'snippet-1')
+ expect(payload.folder_id).toBe('folder-xyz')
+ })
+})
+
+describe('isLoadedSnippet', () => {
+ it('returns true when content is present', () => {
+ const snippet = makeSnippet()
+ expect(isLoadedSnippet(snippet)).toBe(true)
+ })
+
+ it('returns false when content is undefined', () => {
+ const snippet = { ...makeSnippet(), content: undefined }
+ expect(isLoadedSnippet(snippet)).toBe(false)
+ })
+
+ it('narrows the snippet so buildUpsertPayload accepts it', () => {
+ const snippet: SnippetWithContent = makeSnippet()
+ if (isLoadedSnippet(snippet)) {
+ const payload = buildUpsertPayload(snippet, 'snippet-1')
+ expect(payload.id).toBe('snippet-1')
+ } else {
+ throw new Error('expected snippet to be loaded')
+ }
+ })
+})
diff --git a/apps/studio/state/sql-editor/sql-editor-rules.ts b/apps/studio/state/sql-editor/sql-editor-rules.ts
new file mode 100644
index 00000000000..dae2c576d1e
--- /dev/null
+++ b/apps/studio/state/sql-editor/sql-editor-rules.ts
@@ -0,0 +1,64 @@
+import type { SnippetWithContent } from './types'
+import type { UpsertContentPayload } from '@/data/content/content-upsert-mutation'
+
+/**
+ *
+ * A snippet is read-only when it's shared to the project and you are not its
+ * owner. Returns true when editing IS allowed.
+ *
+ */
+export function canEditSnippet(
+ snippet: Pick<SnippetWithContent, 'visibility' | 'owner_id'>,
+ profileId?: number
+): boolean {
+ return !(snippet.visibility === 'project' && snippet.owner_id !== profileId)
+}
+
+export function isSnippetOwner(
+ snippet: Pick<SnippetWithContent, 'owner_id'>,
+ profileId?: number
+): boolean {
+ return profileId === snippet.owner_id
+}
+
+/**
+ *
+ * Shared snippets cannot live in a folder.
+ *
+ */
+export function validateMoveToFolder({
+ visibility,
+ folderId,
+}: {
+ visibility?: SnippetWithContent['visibility']
+ folderId?: string | null
+}): { ok: boolean; error?: string } {
+ if (visibility === 'project' && !!folderId) {
+ return { ok: false, error: 'Shared snippet cannot be within a folder' }
+ }
+ return { ok: true }
+}
+
+export type LoadedSnippet = SnippetWithContent & {
+ content: NonNullable<SnippetWithContent['content']>
+}
+export function isLoadedSnippet(snippet: SnippetWithContent): snippet is LoadedSnippet {
+ return snippet.content != null
+}
+
+export function buildUpsertPayload(snippet: LoadedSnippet, id: string): UpsertContentPayload {
+ const { name, description, visibility, project_id, owner_id, folder_id, content, favorite } =
+ snippet
+ return {
+ id,
+ type: 'sql',
+ name: name ?? 'Untitled',
+ description: description ?? '',
+ visibility: visibility ?? 'user',
+ project_id: project_id ?? 0,
+ owner_id,
+ folder_id: folder_id ?? undefined,
+ favorite: favorite ?? false,
+ content: { ...content, content_id: id },
+ }
+}
diff --git a/apps/studio/state/sql-editor/sql-editor-state.ts b/apps/studio/state/sql-editor/sql-editor-state.ts
index 818f916bc97..38e23e7042b 100644
--- a/apps/studio/state/sql-editor/sql-editor-state.ts
+++ b/apps/studio/state/sql-editor/sql-editor-state.ts
@@ -5,6 +5,7 @@ import { toast } from 'sonner'
import { proxy, ref, snapshot, subscribe, useSnapshot } from 'valtio'
import { devtools, proxyMap } from 'valtio/utils'
+import { buildUpsertPayload, isLoadedSnippet, validateMoveToFolder } from './sql-editor-rules'
import type { SnippetWithContent, StateSnippet, StateSnippetFolder } from './types'
import type { QueryPlanRow } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.types'
import { DiffType } from '@/components/interfaces/SQLEditor/SQLEditor.types'
@@ -241,11 +242,12 @@ export const sqlEditorState = proxy({
let storeFolder = sqlEditorState.folders[id]
const isNewFolder = id === 'new-folder'
const hasChanges = storeFolder.folder.name !== name
+ const folderNameTaken = sqlEditorState.allFolderNames.includes(name)
- if (isNewFolder && sqlEditorState.allFolderNames.includes(name)) {
+ if (isNewFolder && folderNameTaken) {
sqlEditorState.removeFolder(id)
return toast.error('Unable to create new folder: This folder name already exists')
- } else if (hasChanges && sqlEditorState.allFolderNames.includes(name)) {
+ } else if (hasChanges && folderNameTaken) {
storeFolder.status = 'idle'
return toast.error('Unable to update folder: This folder name already exists')
}
@@ -462,38 +464,16 @@ if (typeof window !== 'undefined') {
const folder = state.folders[id]
if (snippet) {
- const {
- name,
- description,
- visibility,
- project_id,
- owner_id,
- folder_id,
- content,
- favorite,
- } = snippet.snippet
-
- if (visibility === 'project' && !!folder_id) {
- toast.error('Shared snippet cannot be within a folder')
- } else {
+ const { visibility, folder_id } = snippet.snippet
+ const result = validateMoveToFolder({ visibility, folderId: folder_id })
+
+ if (!result.ok) {
+ toast.error(result.error)
+ } else if (isLoadedSnippet(snippet.snippet)) {
debouncedUpdateSnippet(
id,
snippet.projectRef,
- {
- id,
- type: 'sql',
- name: name ?? 'Untitled',
- description: description ?? '',
- visibility: visibility ?? 'user',
- project_id: project_id ?? 0,
- owner_id: owner_id,
- folder_id: folder_id ?? undefined,
- favorite: favorite ?? false,
- content: {
- ...content!,
- content_id: id,
- },
- },
+ buildUpsertPayload(snippet.snippet, id),
shouldInvalidate
)
sqlEditorState.needsSaving.delete(id)