Skip to content

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

feat: SQL Snippets (#41112)

Ivan Vasilovf3af2c3d3c88
diff --git a/apps/studio/.env b/apps/studio/.env
index aa475c4b298..bea99a96c27 100644
--- a/apps/studio/.env
+++ b/apps/studio/.env
@@ -25,3 +25,4 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzd
NEXT_PUBLIC_SUPABASE_URL=https://xguihxuzqibwxjnimxev.supabase.co
DOCKER_SOCKET_LOCATION=/var/run/docker.sock
+
diff --git a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
index 788d41c5e41..3a18053eeeb 100644
--- a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
@@ -188,7 +188,7 @@ const MonacoEditor = ({
function handleEditorChange(value: string | undefined) {
tabsSnap.makeActiveTabPermanent()
if (id && value) {
- if (ref && profile !== undefined && project !== undefined) {
+ if (!snippet && ref && profile !== undefined && project !== undefined) {
const snippet = createSqlSnippetSkeletonV2({
idOverride: id,
name: snippetName,
diff --git a/apps/studio/components/interfaces/SQLEditor/MoveQueryModal.tsx b/apps/studio/components/interfaces/SQLEditor/MoveQueryModal.tsx
index 4e1cc639f36..4d17450e9fd 100644
--- a/apps/studio/components/interfaces/SQLEditor/MoveQueryModal.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/MoveQueryModal.tsx
@@ -1,11 +1,12 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { Check, Code, Plus } from 'lucide-react'
+import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import * as z from 'zod'
-import { useParams } from 'common'
+import { IS_PLATFORM, useParams } from 'common'
import { getContentById } from 'data/content/content-id-query'
import { useContentUpsertMutation } from 'data/content/content-upsert-mutation'
import { useSQLSnippetFolderCreateMutation } from 'data/content/sql-folder-create-mutation'
@@ -15,6 +16,7 @@ import {
useSnippetFolders,
useSqlEditorV2StateSnapshot,
} from 'state/sql-editor-v2'
+import { createTabId, useTabsStateSnapshot } from 'state/tabs'
import {
Button,
CommandEmpty_Shadcn_,
@@ -63,12 +65,18 @@ interface MoveQueryModalProps {
export const MoveQueryModal = ({ visible, snippets = [], onClose }: MoveQueryModalProps) => {
const { ref } = useParams()
const snapV2 = useSqlEditorV2StateSnapshot()
+ const tabsSnap = useTabsStateSnapshot()
+ const router = useRouter()
const [open, setOpen] = useState(false)
const [selectedId, setSelectedId] = useState<string>()
const { mutateAsync: createFolder, isPending: isCreatingFolder } =
- useSQLSnippetFolderCreateMutation()
+ useSQLSnippetFolderCreateMutation({
+ onError: (error) => {
+ toast.error(`Failed to create new folder: ${error.message}`)
+ },
+ })
const { mutateAsync: moveSnippetAsync, isPending: isMovingSnippet } = useContentUpsertMutation({
onError: (error) => {
toast.error(`Failed to move query: ${error.message}`)
@@ -140,7 +148,7 @@ export const MoveQueryModal = ({ visible, snippets = [], onClose }: MoveQueryMod
if (snippetContent === undefined) {
return toast.error('Failed to save snippet: Unable to retrieve snippet contents')
} else {
- await moveSnippetAsync({
+ const movedSnippet = await moveSnippetAsync({
projectRef: ref,
payload: {
id: snippet.id,
@@ -154,6 +162,28 @@ export const MoveQueryModal = ({ visible, snippets = [], onClose }: MoveQueryMod
content: snippetContent as any,
},
})
+ if (IS_PLATFORM) {
+ snapV2.updateSnippet({
+ id: snippet.id,
+ snippet: { ...snippet, folder_id: selectedId === 'root' ? null : folderId },
+ skipSave: true,
+ })
+ } else if (movedSnippet) {
+ // On selfhosted, we need to update the state with the moved snippet because the snippet depends on the
+ // folder_id the moved snippet has a different id than the original snippet.
+
+ // remove the old snippet from the state without saving to API
+ snapV2.removeSnippet(snippet.id, true)
+
+ snapV2.addSnippet({ projectRef: ref, snippet: movedSnippet })
+
+ // remove the tab for the old snippet if the snippet was open. Moving can also happen when the tab is not open.
+ const tabId = createTabId('sql', { id: snippet.id })
+ if (tabsSnap.hasTab(tabId)) {
+ tabsSnap.removeTab(tabId)
+ await router.push(`/project/${ref}/sql/${movedSnippet.id}`)
+ }
+ }
}
})
)
@@ -161,16 +191,11 @@ export const MoveQueryModal = ({ visible, snippets = [], onClose }: MoveQueryMod
toast.success(
`Successfully moved ${snippets.length === 1 ? `"${snippets[0].name}"` : `${snippets.length} snippets`} to ${selectedId === 'root' ? 'the root of the editor' : selectedFolder}`
)
- snippets.forEach((snippet) => {
- snapV2.updateSnippet({
- id: snippet.id,
- snippet: { ...snippet, folder_id: selectedId === 'root' ? null : folderId },
- skipSave: true,
- })
- })
+
onClose()
} catch (error: any) {
- toast.error(`Failed to create new folder: ${error.message}`)
+ // error will be handled by the mutation's onError callback
+ console.error('Error moving snippets:', error)
}
}
diff --git a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
index c1f7675a84a..9201b8f032f 100644
--- a/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
@@ -15,6 +15,7 @@ import { Snippet } from 'data/content/sql-folders-query'
import type { SqlSnippet } from 'data/content/sql-snippets-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { IS_PLATFORM } from 'lib/constants'
import { useRouter } from 'next/router'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
import { createTabId, useTabsStateSnapshot } from 'state/tabs'
@@ -103,7 +104,7 @@ const RenameQueryModal = ({
snapV2.addSnippet({ projectRef: ref, snippet: localSnippet })
}
- await upsertContent({
+ const changedSnippet = await upsertContent({
projectRef: ref,
payload: {
...localSnippet,
@@ -112,10 +113,27 @@ const RenameQueryModal = ({
} as UpsertContentPayload,
})
- snapV2.renameSnippet({ id, name: nameInput, description: descriptionInput })
+ if (IS_PLATFORM) {
+ snapV2.renameSnippet({ id, name: nameInput, description: descriptionInput })
- const tabId = createTabId('sql', { id })
- tabsSnap.updateTab(tabId, { label: nameInput })
+ const tabId = createTabId('sql', { id })
+ tabsSnap.updateTab(tabId, { label: nameInput })
+ } else if (changedSnippet) {
+ // In self-hosted, the snippet also updates the id when renaming it. This code is to ensure the previous snippet
+ // is removed, new one is added, tab state is updated and the router is updated.
+
+ // remove the old snippet from the state without saving to API
+ snapV2.removeSnippet(id, true)
+
+ snapV2.addSnippet({ projectRef: ref, snippet: changedSnippet })
+
+ // remove the tab for the old snippet if the snippet was open. Renaming can also happen when the tab is not open.
+ const tabId = createTabId('sql', { id })
+ if (tabsSnap.hasTab(tabId)) {
+ tabsSnap.removeTab(tabId)
+ await router.push(`/project/${ref}/sql/${changedSnippet.id}`)
+ }
+ }
toast.success('Successfully renamed snippet!')
if (onComplete) onComplete()
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index b881e15ff82..8557a1b6643 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -124,7 +124,7 @@ export const SQLEditor = () => {
// shows up when clicking on the SQL Editor while being in the SQL editor on a random snippet.
const [generatedNewSnippetName, generatedId] = useMemo(() => {
const name = generateSnippetTitle()
- return [name, generateUuid([name])]
+ return [name, generateUuid([`${name}.sql`])]
}, [urlId])
// the id is stable across renders - it depends either on the url or on the memoized generated id
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
index c4661a6f14c..f18eb79c5ec 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
@@ -27,7 +27,7 @@ export const createSqlSnippetSkeletonV2 = ({
*/
idOverride?: string
}): SnippetWithContent => {
- const id = idOverride ?? generateUuid([folder_id, name])
+ const id = idOverride ?? generateUuid([folder_id, `${name}.sql`])
return {
...NEW_SQL_SNIPPET_SKELETON,
diff --git a/apps/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx b/apps/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx
index af5a7161460..6ad7eb1e82a 100644
--- a/apps/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.utils.tsx
@@ -26,9 +26,7 @@ export const generateToolRoutes = (ref?: string, project?: Project, features?: {
key: 'sql',
label: 'SQL Editor',
icon: <SqlEditor size={ICON_SIZE} strokeWidth={ICON_STROKE_WIDTH} />,
- link: !IS_PLATFORM
- ? `/project/${ref}/sql/1`
- : ref && (isProjectBuilding ? buildingUrl : `/project/${ref}/sql`),
+ link: ref && (isProjectBuilding ? buildingUrl : `/project/${ref}/sql`),
},
]
}
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
index b35daf3efb5..a6af02d7eef 100644
--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
@@ -9,7 +9,6 @@ import { toast } from 'sonner'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useLocalStorage } from 'hooks/misc/useLocalStorage'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
-import { IS_PLATFORM } from 'lib/constants'
import { useProfile } from 'lib/profile'
import { getAppStateSnapshot } from 'state/app-state'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
@@ -149,12 +148,10 @@ export const SQLEditorMenu = () => {
<FilePlus size={14} />
Create a new snippet
</DropdownMenuItem>
- {IS_PLATFORM && (
- <DropdownMenuItem className="gap-x-2" onClick={() => createNewFolder()}>
- <FolderPlus size={14} />
- Create a new folder
- </DropdownMenuItem>
- )}
+ <DropdownMenuItem className="gap-x-2" onClick={() => createNewFolder()}>
+ <FolderPlus size={14} />
+ Create a new folder
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
index 6f0621235c9..680f80f1f0d 100644
--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
@@ -90,6 +90,7 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
hasNextPage,
fetchNextPage,
isFetchingNextPage,
+ error: snippetsFoldersError,
} = useSQLSnippetFoldersQuery({ projectRef, sort }, { placeholderData: keepPreviousData })
const [subResults, setSubResults] = useState<{
@@ -147,10 +148,19 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
)
const folders = useSnippetFolders(projectRef!)
- const { data: snippetCountData } = useContentCountQuery({
+ const { data: snippetCountData, error: snippetCountError } = useContentCountQuery({
projectRef,
type: 'sql',
})
+
+ useEffect(() => {
+ if (snippetCountError || snippetsFoldersError) {
+ toast.error(
+ snippetCountError?.message || snippetsFoldersError?.message || 'Failed to load snippets'
+ )
+ }
+ }, [snippetCountError, snippetsFoldersError])
+
const numPrivateSnippets = snippetCountData?.private ?? 0
const privateSnippetsTreeState = useMemo(
diff --git a/apps/studio/lib/api/snippets.constants.ts b/apps/studio/lib/api/snippets.constants.ts
new file mode 100644
index 00000000000..c89918b0422
--- /dev/null
+++ b/apps/studio/lib/api/snippets.constants.ts
@@ -0,0 +1 @@
+export const SNIPPETS_DIR = process.env.SNIPPETS_MANAGEMENT_FOLDER ?? ''
diff --git a/apps/studio/lib/api/snippets.utils.test.ts b/apps/studio/lib/api/snippets.utils.test.ts
new file mode 100644
index 00000000000..624c8b6673c
--- /dev/null
+++ b/apps/studio/lib/api/snippets.utils.test.ts
@@ -0,0 +1,1634 @@
+import fs from 'fs/promises'
+import path from 'path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { generateDeterministicUuid } from './snippets.browser'
+import {
+ createFolder,
+ deleteFolder,
+ deleteSnippet,
+ getFilesystemEntries,
+ getFolders,
+ getSnippet,
+ getSnippets,
+ saveSnippet,
+ updateSnippet,
+ type Snippet,
+} from './snippets.utils'
+
+// Mock fs/promises
+vi.mock('fs/promises')
+const mockedFS = vi.mocked(fs)
+
+// Mock SNIPPETS_DIR from constants
+vi.mock('./snippets.constants', () => ({
+ SNIPPETS_DIR: '/mock/snippets/dir',
+}))
+
+describe('snippets.utils', () => {
+ const MOCK_SNIPPETS_DIR = '/mock/snippets/dir'
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ vi.resetAllMocks()
+ })
+
+ describe('getFilesystemEntries', () => {
+ it('should create the snippets directory if it does not exist', async () => {
+ const accessError = new Error('Directory not found')
+ mockedFS.access.mockRejectedValue(accessError)
+ mockedFS.mkdir.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await getFilesystemEntries()
+
+ expect(mockedFS.access).toHaveBeenCalledWith(MOCK_SNIPPETS_DIR)
+ expect(mockedFS.mkdir).toHaveBeenCalledWith(MOCK_SNIPPETS_DIR, { recursive: true })
+ })
+
+ it('should read and parse SQL files from the snippets directory', async () => {
+ const files = [
+ {
+ name: 'snippet1.sql',
+ isDirectory: () => false,
+ isFile: () => true,
+ },
+ {
+ name: 'snippet2.sql',
+ isDirectory: () => false,
+ isFile: () => true,
+ },
+ {
+ name: 'not-sql.txt',
+ isDirectory: () => false,
+ isFile: () => true,
+ },
+ ]
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue(files as any)
+ mockedFS.readFile
+ .mockResolvedValueOnce('SELECT * FROM users;')
+ .mockResolvedValueOnce('SELECT * FROM posts;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const entries = await getFilesystemEntries()
+
+ expect(entries).toHaveLength(2)
+ expect(entries[0].name).toBe('snippet1')
+ expect(entries[0].content).toBe('SELECT * FROM users;')
+ expect(entries[0].type).toBe('file')
+ expect(entries[1].name).toBe('snippet2')
+ expect(entries[1].content).toBe('SELECT * FROM posts;')
+ expect(entries[1].type).toBe('file')
+ expect(mockedFS.readFile).toHaveBeenCalledTimes(2)
+ })
+
+ it('should return empty array when no SQL files exist', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'not-sql.txt', isDirectory: () => false, isFile: () => true },
+ ] as any)
+
+ const entries = await getFilesystemEntries()
+
+ expect(entries).toEqual([])
+ })
+
+ it('should read SQL files from subdirectories (folders)', async () => {
+ // Mock fs.Dirent objects for different file types
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ // Mock the main directory structure
+ const mainDirItems = [
+ createMockDirent('root-snippet.sql', false),
+ createMockDirent('folder1', true),
+ createMockDirent('not-sql.txt', false),
+ ]
+
+ // Mock folder1 contents
+ const folder1Items = [createMockDirent('folder1-snippet.sql', false)]
+
+ mockedFS.access.mockResolvedValue(undefined)
+
+ // Mock readdir to return different results based on the path
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve(mainDirItems as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'folder1')) {
+ return Promise.resolve(folder1Items as any)
+ }
+ return Promise.resolve([])
+ })
+
+ // Mock readFile to return different content based on the file
+ mockedFS.readFile.mockImplementation((filePath: any) => {
+ const fileName = path.basename(filePath as string)
+ switch (fileName) {
+ case 'root-snippet.sql':
+ return Promise.resolve('SELECT * FROM root;')
+ case 'folder1-snippet.sql':
+ return Promise.resolve('SELECT * FROM folder1_table;')
+ default:
+ return Promise.reject(new Error('File not found'))
+ }
+ })
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const entries = await getFilesystemEntries()
+
+ // Should find 1 folder and 2 SQL files
+ expect(entries).toHaveLength(3)
+
+ const folders = entries.filter((e) => e.type === 'folder')
+ const files = entries.filter((e) => e.type === 'file')
+
+ expect(folders).toHaveLength(1)
+ expect(folders[0].name).toBe('folder1')
+ expect(folders[0].folderId).toBe(null) // Folders are always at root level
+
+ expect(files).toHaveLength(2)
+ const rootFile = files.find((f) => f.name === 'root-snippet')
+ const folderFile = files.find((f) => f.name === 'folder1-snippet')
+
+ expect(rootFile?.folderId).toBe(null)
+ expect(folderFile?.folderId).toBe(generateDeterministicUuid(['folder1']))
+ })
+
+ it('should skip subdirectories inside folders (not supported)', async () => {
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ const mainDirItems = [createMockDirent('folder1', true)]
+ const folder1Items = [
+ createMockDirent('snippet.sql', false),
+ createMockDirent('subfolder', true), // This should be skipped
+ ]
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve(mainDirItems as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'folder1')) {
+ return Promise.resolve(folder1Items as any)
+ }
+ return Promise.resolve([])
+ })
+
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM table;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const entries = await getFilesystemEntries()
+
+ // Should only find 1 folder and 1 file (subfolder should be skipped)
+ expect(entries).toHaveLength(2)
+ expect(entries.filter((e) => e.type === 'folder')).toHaveLength(1)
+ expect(entries.filter((e) => e.type === 'file')).toHaveLength(1)
+ })
+
+ it('should handle empty SQL files', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'empty.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const entries = await getFilesystemEntries()
+
+ expect(entries).toHaveLength(1)
+ expect(entries[0].content).toBe('')
+ })
+
+ it('should handle file read errors gracefully', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'error.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockRejectedValue(new Error('Permission denied'))
+
+ await expect(getFilesystemEntries()).rejects.toThrow('Permission denied')
+ })
+
+ it('should handle mkdir failure', async () => {
+ mockedFS.access.mockRejectedValue(new Error('Directory not found'))
+ mockedFS.mkdir.mockRejectedValue(new Error('Permission denied'))
+
+ await expect(getFilesystemEntries()).rejects.toThrow('Permission denied')
+ })
+ })
+
+ describe('getSnippet', () => {
+ it('should get a specific snippet by id', async () => {
+ const snippetName = 'test-snippet'
+ const snippetId = generateDeterministicUuid([`${snippetName}.sql`])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM test;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const snippet = await getSnippet(snippetId)
+
+ // The snippet ID is generated from the full filename in buildSnippet
+ expect(snippet.id).toBe(generateDeterministicUuid([`${snippetName}.sql`]))
+ expect(snippet.name).toBe(snippetName)
+ expect(snippet.content.sql).toBe('SELECT * FROM test;')
+ expect(snippet.folder_id).toBe(null)
+ })
+
+ it('should get a snippet from a folder', async () => {
+ const folderName = 'my-folder'
+ const folderId = generateDeterministicUuid([folderName])
+ const snippetName = 'folder-snippet'
+ const snippetId = generateDeterministicUuid([folderId, `${snippetName}.sql`])
+
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve([createMockDirent(folderName, true)] as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, folderName)) {
+ return Promise.resolve([createMockDirent(`${snippetName}.sql`, false)] as any)
+ }
+ return Promise.resolve([])
+ })
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM folder_table;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const snippet = await getSnippet(snippetId)
+
+ expect(snippet.id).toBe(generateDeterministicUuid([folderId, `${snippetName}.sql`]))
+ expect(snippet.name).toBe(snippetName)
+ expect(snippet.content.sql).toBe('SELECT * FROM folder_table;')
+ expect(snippet.folder_id).toBe(generateDeterministicUuid(['my-folder']))
+ })
+
+ it('should throw error when snippet not found', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(getSnippet('non-existent-id')).rejects.toThrow(
+ 'Snippet with id non-existent-id not found'
+ )
+ })
+ })
+
+ describe('getSnippets', () => {
+ it('should get all snippets from root folder', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'snippet2.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'folder1', isDirectory: () => true, isFile: () => false },
+ ] as any)
+ mockedFS.readFile
+ .mockResolvedValueOnce('SELECT * FROM table1;')
+ .mockResolvedValueOnce('SELECT * FROM table2;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ folderId: null, sort: 'name', sortOrder: 'asc' })
+
+ expect(result.snippets).toHaveLength(2)
+ expect(result.snippets[0].name).toBe('snippet1')
+ expect(result.snippets[1].name).toBe('snippet2')
+ expect(result.snippets[0].folder_id).toBe(null)
+ expect(result.snippets[1].folder_id).toBe(null)
+ expect(result.cursor).toBeUndefined()
+ })
+
+ it('should get snippets from a specific folder', async () => {
+ const folderId = generateDeterministicUuid(['my-folder'])
+
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve([createMockDirent('my-folder', true)] as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'my-folder')) {
+ return Promise.resolve([createMockDirent('folder-snippet.sql', false)] as any)
+ }
+ return Promise.resolve([])
+ })
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM folder_table;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ folderId })
+
+ expect(result.snippets).toHaveLength(1)
+ expect(result.snippets[0].name).toBe('folder-snippet')
+ expect(result.snippets[0].folder_id).toBe(folderId)
+ })
+
+ it('should return empty result when no snippets in folder', async () => {
+ const folderId = generateDeterministicUuid(['empty-folder'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ const result = await getSnippets({ folderId })
+
+ expect(result.snippets).toEqual([])
+ expect(result.cursor).toBeUndefined()
+ })
+
+ it('should filter snippets by search term across all folders', async () => {
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve([
+ createMockDirent('user-query.sql', false),
+ createMockDirent('admin-report.sql', false),
+ createMockDirent('test-user-data.sql', false),
+ createMockDirent('my-folder', true),
+ ] as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'my-folder')) {
+ return Promise.resolve([createMockDirent('user-permissions.sql', false)] as any)
+ }
+ return Promise.resolve([])
+ })
+ mockedFS.readFile.mockImplementation((filePath: any) => {
+ const fileName = path.basename(filePath as string)
+ return Promise.resolve(`SELECT * FROM ${fileName.replace('.sql', '')};`)
+ })
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ searchTerm: 'user', sort: 'name', sortOrder: 'asc' })
+
+ expect(result.snippets).toHaveLength(3)
+ expect(result.snippets.map((s) => s.name)).toEqual([
+ 'test-user-data',
+ 'user-permissions',
+ 'user-query',
+ ])
+ })
+
+ it('should sort snippets by name in ascending order', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'zebra.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'apple.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'banana.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ sort: 'name', sortOrder: 'asc' })
+
+ expect(result.snippets.map((s) => s.name)).toEqual(['apple', 'banana', 'zebra'])
+ })
+
+ it('should sort snippets by name in descending order', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'zebra.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'apple.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'banana.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ sort: 'name', sortOrder: 'desc' })
+
+ expect(result.snippets.map((s) => s.name)).toEqual(['zebra', 'banana', 'apple'])
+ })
+
+ it('should sort snippets by creation date', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'newest.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'oldest.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'middle.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockImplementation((filePath: any) => {
+ const fileName = path.basename(filePath as string)
+ switch (fileName) {
+ case 'newest.sql':
+ return Promise.resolve({ birthtime: new Date('2023-03-01') } as any)
+ case 'oldest.sql':
+ return Promise.resolve({ birthtime: new Date('2023-01-01') } as any)
+ case 'middle.sql':
+ return Promise.resolve({ birthtime: new Date('2023-02-01') } as any)
+ default:
+ return Promise.resolve({ birthtime: new Date('2023-01-01') } as any)
+ }
+ })
+
+ // Test descending order (newest first - default behavior)
+ const resultDesc = await getSnippets({ sort: 'inserted_at', sortOrder: 'desc' })
+ expect(resultDesc.snippets.map((s) => s.name)).toEqual(['newest', 'middle', 'oldest'])
+
+ // Test ascending order (oldest first)
+ const resultAsc = await getSnippets({ sort: 'inserted_at', sortOrder: 'asc' })
+ expect(resultAsc.snippets.map((s) => s.name)).toEqual(['oldest', 'middle', 'newest'])
+ })
+
+ it('should paginate results with limit', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'snippet2.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'snippet3.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'snippet4.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ limit: 2, sort: 'name', sortOrder: 'asc' })
+
+ expect(result.snippets).toHaveLength(2)
+ expect(result.snippets.map((s) => s.name)).toEqual(['snippet1', 'snippet2'])
+ expect(result.cursor).toBeDefined() // Should have a cursor for next page
+ })
+
+ it('should use cursor for pagination', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'snippet2.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'snippet3.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ // Get first page
+ const firstPage = await getSnippets({ limit: 1, sort: 'name', sortOrder: 'asc' })
+ expect(firstPage.snippets).toHaveLength(1)
+ expect(firstPage.snippets[0].name).toBe('snippet1')
+ expect(firstPage.cursor).toBeDefined()
+
+ // Get second page using cursor
+ const secondPage = await getSnippets({
+ cursor: firstPage.cursor,
+ limit: 1,
+ sort: 'name',
+ sortOrder: 'asc',
+ })
+ expect(secondPage.snippets).toHaveLength(1)
+ expect(secondPage.snippets[0].name).toBe('snippet2')
+ })
+
+ it('should handle invalid cursor gracefully', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ cursor: 'invalid-cursor-id' })
+
+ expect(result.snippets).toHaveLength(1) // Should return all snippets
+ expect(result.snippets[0].name).toBe('snippet1')
+ })
+
+ it('should use default parameters when none provided', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({})
+
+ expect(result.snippets).toHaveLength(1)
+ expect(result.cursor).toBeUndefined()
+ // Default sort should be by inserted_at desc
+ })
+
+ it('should handle empty search term', async () => {
+ const folderId = generateDeterministicUuid(['my-folder'])
+
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve([
+ createMockDirent('root-snippet.sql', false),
+ createMockDirent('my-folder', true),
+ ] as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'my-folder')) {
+ return Promise.resolve([createMockDirent('folder-snippet.sql', false)] as any)
+ }
+ return Promise.resolve([])
+ })
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ // Empty search term should filter by folderId
+ const result = await getSnippets({ searchTerm: ' ', folderId })
+
+ expect(result.snippets).toHaveLength(1)
+ expect(result.snippets[0].name).toBe('folder-snippet')
+ })
+
+ it('should handle filesystem errors', async () => {
+ mockedFS.access.mockRejectedValue(new Error('Directory not accessible'))
+ mockedFS.mkdir.mockRejectedValue(new Error('Directory not accessible'))
+
+ await expect(getSnippets({})).rejects.toThrow('Directory not accessible')
+ })
+
+ it('should return correct snippet structure', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM users;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01T10:00:00Z') } as any)
+
+ const result = await getSnippets({})
+
+ expect(result.snippets).toHaveLength(1)
+ const snippet = result.snippets[0]
+
+ expect(snippet).toMatchObject({
+ name: 'test-snippet',
+ type: 'sql',
+ content: {
+ sql: 'SELECT * FROM users;',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: null,
+ owner_id: 1,
+ owner: { id: 1, username: 'johndoe' },
+ updated_by: { id: 1, username: 'johndoe' },
+ })
+
+ expect(snippet.id).toBeDefined()
+ expect(snippet.inserted_at).toBe('2023-01-01T10:00:00.000Z')
+ expect(snippet.updated_at).toBe('2023-01-01T10:00:00.000Z')
+ })
+
+ it('should perform case-insensitive search', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'USER-query.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'admin-report.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'Test-User-Data.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ searchTerm: 'user', sort: 'name', sortOrder: 'asc' })
+
+ expect(result.snippets).toHaveLength(2)
+ expect(result.snippets.map((s) => s.name)).toEqual(['Test-User-Data', 'USER-query'])
+ })
+
+ it('should perform case-insensitive name sorting', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'zebra.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'Apple.sql', isDirectory: () => false, isFile: () => true },
+ { name: 'banana.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ sort: 'name', sortOrder: 'asc' })
+
+ expect(result.snippets.map((s) => s.name)).toEqual(['Apple', 'banana', 'zebra'])
+ })
+
+ it('should validate limit parameter', async () => {
+ await expect(getSnippets({ limit: 0 })).rejects.toThrow('Limit must be a positive number')
+ await expect(getSnippets({ limit: -5 })).rejects.toThrow('Limit must be a positive number')
+ await expect(getSnippets({ limit: 1001 })).rejects.toThrow('Limit cannot exceed 1000')
+ })
+
+ it('should handle large valid limit', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'snippet1.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT 1;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await getSnippets({ limit: 1000 })
+
+ expect(result.snippets).toHaveLength(1)
+ })
+ })
+
+ describe('saveSnippet', () => {
+ it('should save a snippet to the filesystem', async () => {
+ const mockSnippet: Snippet = {
+ id: 'test-id',
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: 'test-snippet',
+ description: 'Test snippet',
+ favorite: false,
+ content: {
+ sql: 'SELECT * FROM test;',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: null,
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ // Mock that no existing snippet exists
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+ mockedFS.writeFile.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await saveSnippet(mockSnippet)
+
+ expect(mockedFS.writeFile).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'test-snippet.sql'),
+ 'SELECT * FROM test;',
+ 'utf-8'
+ )
+ expect(result.name).toBe('test-snippet')
+ expect(result.content.sql).toBe('SELECT * FROM test;')
+ })
+
+ it('should handle empty content', async () => {
+ const mockSnippet: Snippet = {
+ id: 'test-id',
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: 'empty-snippet',
+ description: '',
+ favorite: false,
+ content: {
+ sql: '',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: null,
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+ mockedFS.writeFile.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await saveSnippet(mockSnippet)
+
+ expect(mockedFS.writeFile).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'empty-snippet.sql'),
+ '',
+ 'utf-8'
+ )
+ expect(result.content.sql).toBe('')
+ })
+
+ it('should throw error when snippet already exists', async () => {
+ const mockSnippet: Snippet = {
+ id: generateDeterministicUuid(['existing-snippet.sql']),
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: 'existing-snippet',
+ description: '',
+ favorite: false,
+ content: {
+ sql: 'SELECT * FROM test;',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: null,
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ // Mock that snippet already exists
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM existing;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ await expect(saveSnippet(mockSnippet)).rejects.toThrow(
+ `Snippet with id ${mockSnippet.id} already exists`
+ )
+ })
+
+ it('should save snippet to a folder when folder_id is provided', async () => {
+ const mockSnippet: Snippet = {
+ id: 'test-id',
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: 'folder-snippet',
+ description: '',
+ favorite: false,
+ content: {
+ sql: 'SELECT * FROM folder_table;',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: generateDeterministicUuid(['test-folder']),
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'test-folder', isDirectory: () => true, isFile: () => false },
+ ] as any)
+ mockedFS.writeFile.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await saveSnippet(mockSnippet)
+
+ expect(mockedFS.writeFile).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'test-folder', 'folder-snippet.sql'),
+ 'SELECT * FROM folder_table;',
+ 'utf-8'
+ )
+ expect(result.folder_id).toBe(generateDeterministicUuid(['test-folder']))
+ })
+
+ it('should throw error when folder_id is provided but folder does not exist', async () => {
+ const mockSnippet: Snippet = {
+ id: 'test-id',
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: 'orphan-snippet',
+ description: '',
+ favorite: false,
+ content: {
+ sql: 'SELECT * FROM table;',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: 'non-existent-folder-id',
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(saveSnippet(mockSnippet)).rejects.toThrow(
+ 'Folder with id non-existent-folder-id not found'
+ )
+ })
+
+ it('should reject path traversal attempts with ../', async () => {
+ const mockSnippet: Snippet = {
+ id: 'test-id',
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: '../malicious-snippet',
+ description: '',
+ favorite: false,
+ content: {
+ sql: 'SELECT * FROM test;',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: null,
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(saveSnippet(mockSnippet)).rejects.toThrow(
+ 'Invalid name: path traversal or null bytes detected'
+ )
+ })
+
+ it('should reject path traversal attempts with nested directories', async () => {
+ const mockSnippet: Snippet = {
+ id: 'test-id',
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: 'foo/bar/snippet',
+ description: '',
+ favorite: false,
+ content: {
+ sql: 'SELECT * FROM test;',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: null,
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(saveSnippet(mockSnippet)).rejects.toThrow(
+ 'Invalid name: path traversal or null bytes detected'
+ )
+ })
+
+ it('should reject names with null bytes', async () => {
+ const mockSnippet: Snippet = {
+ id: 'test-id',
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: 'malicious\0snippet',
+ description: '',
+ favorite: false,
+ content: {
+ sql: 'SELECT * FROM test;',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: null,
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(saveSnippet(mockSnippet)).rejects.toThrow(
+ 'Invalid name: path traversal or null bytes detected'
+ )
+ })
+
+ it('should reject absolute path attempts', async () => {
+ const mockSnippet: Snippet = {
+ id: 'test-id',
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: '/etc/passwd',
+ description: '',
+ favorite: false,
+ content: {
+ sql: 'SELECT * FROM test;',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: null,
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(saveSnippet(mockSnippet)).rejects.toThrow(
+ 'Invalid name: path traversal or null bytes detected'
+ )
+ })
+
+ it('should allow valid names with special characters', async () => {
+ const mockSnippet: Snippet = {
+ id: 'test-id',
+ inserted_at: '2023-01-01T00:00:00.000Z',
+ updated_at: '2023-01-01T00:00:00.000Z',
+ type: 'sql',
+ name: 'my-snippet_v2 (copy)',
+ description: '',
+ favorite: false,
+ content: {
+ sql: 'SELECT * FROM test;',
+ content_id: 'content-id',
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: null,
+ owner_id: 1,
+ owner: { id: 1, username: 'testuser' },
+ updated_by: { id: 1, username: 'testuser' },
+ }
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+ mockedFS.writeFile.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const result = await saveSnippet(mockSnippet)
+
+ expect(result.name).toBe('my-snippet_v2 (copy)')
+ expect(mockedFS.writeFile).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'my-snippet_v2 (copy).sql'),
+ 'SELECT * FROM test;',
+ 'utf-8'
+ )
+ })
+ })
+
+ describe('deleteSnippet', () => {
+ it('should delete a snippet file', async () => {
+ const snippetId = generateDeterministicUuid(['test-snippet.sql'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM test;')
+ mockedFS.unlink.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ await deleteSnippet(snippetId)
+
+ expect(mockedFS.unlink).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, `test-snippet.sql`))
+ })
+
+ it('should not throw error when file does not exist', async () => {
+ const snippetId = generateDeterministicUuid(['test-snippet.sql'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM test;')
+
+ const error = new Error('File not found') as NodeJS.ErrnoException
+ error.code = 'ENOENT'
+ mockedFS.unlink.mockRejectedValue(error)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ await expect(deleteSnippet(snippetId)).resolves.not.toThrow()
+ })
+
+ it('should throw error for other filesystem errors', async () => {
+ const snippetId = generateDeterministicUuid(['test-snippet.sql'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'test-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM test;')
+
+ const error = new Error('Permission denied') as NodeJS.ErrnoException
+ error.code = 'EACCES'
+ mockedFS.unlink.mockRejectedValue(error)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ await expect(deleteSnippet(snippetId)).rejects.toThrow('Permission denied')
+ })
+
+ it('should throw error when snippet not found', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(deleteSnippet('non-existent-id')).rejects.toThrow(
+ 'Snippet with id non-existent-id not found'
+ )
+ })
+
+ it('should delete a snippet file from a folder', async () => {
+ const folderName = 'my-folder'
+ const folderId = generateDeterministicUuid([folderName])
+ const snippetName = 'folder-snippet'
+ const snippetId = generateDeterministicUuid([folderId, `${snippetName}.sql`])
+
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve([createMockDirent(folderName, true)] as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, folderName)) {
+ return Promise.resolve([createMockDirent('folder-snippet.sql', false)] as any)
+ }
+ return Promise.resolve([])
+ })
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM folder_table;')
+ mockedFS.unlink.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ await deleteSnippet(snippetId)
+
+ expect(mockedFS.unlink).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'my-folder', 'folder-snippet.sql')
+ )
+ })
+ })
+
+ describe('updateSnippet', () => {
+ it('should update an existing snippet', async () => {
+ const id = generateDeterministicUuid(['existing-snippet.sql'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+
+ // First call to getFilesystemEntries - find existing snippet
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+
+ // Read the existing snippet content
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const updates = { name: 'updated-snippet', content: { sql: 'SELECT * FROM new;' } }
+
+ const result = await updateSnippet(id, updates)
+
+ expect(mockedFS.unlink).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql')
+ )
+ expect(mockedFS.writeFile).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'updated-snippet.sql'),
+ 'SELECT * FROM new;',
+ 'utf-8'
+ )
+ expect(result.name).toBe('updated-snippet')
+ expect(result.content.sql).toBe('SELECT * FROM new;')
+ })
+
+ it('should throw error when snippet not found', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(updateSnippet('non-existent-id', {})).rejects.toThrow(
+ 'Snippet with id non-existent-id not found'
+ )
+ })
+
+ it('should update only provided fields', async () => {
+ const id = generateDeterministicUuid(['existing-snippet.sql'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ // Mock readdir for both getFilesystemEntries calls (initial and final)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ // Mock readFile for both calls (initial and final)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+ mockedFS.writeFile.mockResolvedValue(undefined)
+
+ const updates = {
+ name: 'new-name',
+ }
+
+ const result = await updateSnippet(id, updates)
+
+ expect(result.name).toBe('new-name')
+ expect(result.content.sql).toBe('SELECT * FROM old;')
+ })
+
+ it('should move snippet to a folder when folder_id is updated', async () => {
+ const id = generateDeterministicUuid(['existing-snippet.sql'])
+ const targetFolderId = generateDeterministicUuid(['target-folder'])
+
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ // Mock existing snippet in root directory
+ mockedFS.access.mockResolvedValue(undefined)
+
+ // Mock multiple readdir calls - the function calls getFilesystemEntries twice
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve([
+ createMockDirent('existing-snippet.sql', false),
+ createMockDirent('target-folder', true),
+ ] as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'target-folder')) {
+ return Promise.resolve([])
+ }
+ return Promise.resolve([])
+ })
+
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')
+ mockedFS.writeFile.mockResolvedValue(undefined)
+ mockedFS.unlink.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const updates = { folder_id: targetFolderId }
+
+ const result = await updateSnippet(id, updates)
+
+ // Should write to the folder path
+ expect(mockedFS.writeFile).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'target-folder', 'existing-snippet.sql'),
+ 'SELECT * FROM old;',
+ 'utf-8'
+ )
+ // Should delete the old file from root
+ expect(mockedFS.unlink).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql')
+ )
+ expect(result.folder_id).toBe(targetFolderId)
+ })
+
+ it('should move snippet from folder to root when folder_id is set to null', async () => {
+ const folderName = 'source-folder'
+ const folderId = generateDeterministicUuid([folderName])
+ const id = generateDeterministicUuid([folderId, 'existing-snippet.sql'])
+
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ mockedFS.access.mockResolvedValue(undefined)
+
+ // Mock existing snippet in a folder - the function expects the snippet to have folder_id set
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve([createMockDirent(folderName, true)] as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, folderName)) {
+ return Promise.resolve([createMockDirent('existing-snippet.sql', false)] as any)
+ }
+ return Promise.resolve([])
+ })
+
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM folder;')
+ mockedFS.writeFile.mockResolvedValue(undefined)
+ mockedFS.unlink.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const updates = { folder_id: null }
+
+ const result = await updateSnippet(id, updates)
+
+ // Should write to the root path
+ expect(mockedFS.writeFile).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql'),
+ 'SELECT * FROM folder;',
+ 'utf-8'
+ )
+ // Should delete the old file from folder
+ expect(mockedFS.unlink).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'source-folder', 'existing-snippet.sql')
+ )
+ expect(result.folder_id).toBe(null)
+ })
+
+ it('should throw error when trying to move to non-existent folder', async () => {
+ const id = generateDeterministicUuid(['existing-snippet.sql'])
+ const nonExistentFolderId = 'non-existent-folder-id'
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM table;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const updates = { folder_id: nonExistentFolderId }
+
+ await expect(updateSnippet(id, updates)).rejects.toThrow(
+ `Folder with id ${nonExistentFolderId} not found`
+ )
+ })
+
+ it('should handle renaming snippet while moving to folder', async () => {
+ const id = generateDeterministicUuid(['existing-snippet.sql'])
+ const targetFolderId = generateDeterministicUuid(['target-folder'])
+
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve([
+ createMockDirent('existing-snippet.sql', false),
+ createMockDirent('target-folder', true),
+ ] as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'target-folder')) {
+ return Promise.resolve([])
+ }
+ return Promise.resolve([])
+ })
+
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')
+ mockedFS.writeFile.mockResolvedValue(undefined)
+ mockedFS.unlink.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const updates = {
+ name: 'renamed-snippet',
+ folder_id: targetFolderId,
+ content: { sql: 'SELECT * FROM new;' },
+ }
+
+ const result = await updateSnippet(id, updates as any)
+
+ // Should write to the folder path with new name
+ expect(mockedFS.writeFile).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'target-folder', 'renamed-snippet.sql'),
+ 'SELECT * FROM new;',
+ 'utf-8'
+ )
+ // Should delete the old file from root with old name
+ expect(mockedFS.unlink).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql')
+ )
+ expect(result.name).toBe('renamed-snippet')
+ expect(result.folder_id).toBe(targetFolderId)
+ expect(result.content.sql).toBe('SELECT * FROM new;')
+ })
+
+ it('should update content to empty string', async () => {
+ const id = generateDeterministicUuid(['existing-snippet.sql'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')
+ mockedFS.writeFile.mockResolvedValue(undefined)
+ mockedFS.unlink.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const updates = { content: { sql: '' } }
+
+ const result = await updateSnippet(id, updates as any)
+
+ expect(result.content.sql).toBe('')
+ expect(mockedFS.writeFile).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'existing-snippet.sql'),
+ '',
+ 'utf-8'
+ )
+ })
+
+ it('should handle old file deletion errors other than ENOENT', async () => {
+ const id = generateDeterministicUuid(['existing-snippet.sql'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const error = new Error('Permission denied') as NodeJS.ErrnoException
+ error.code = 'EACCES'
+ mockedFS.unlink.mockRejectedValue(error)
+
+ const updates = { name: 'new-name' }
+
+ await expect(updateSnippet(id, updates)).rejects.toThrow('Permission denied')
+ })
+
+ it('should continue when old file deletion fails with ENOENT', async () => {
+ const id = generateDeterministicUuid(['existing-snippet.sql'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'existing-snippet.sql', isDirectory: () => false, isFile: () => true },
+ ] as any)
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM old;')
+ mockedFS.writeFile.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const error = new Error('File not found') as NodeJS.ErrnoException
+ error.code = 'ENOENT'
+ mockedFS.unlink.mockRejectedValue(error)
+
+ const updates = { name: 'new-name' }
+
+ const result = await updateSnippet(id, updates)
+
+ expect(result.name).toBe('new-name')
+ expect(result.content.sql).toBe('SELECT * FROM old;')
+ })
+
+ it('should throw error when moving snippet to folder that already contains snippet with same name', async () => {
+ const snippetName = 'existing-snippet'
+ const existingSnippetId = generateDeterministicUuid([`${snippetName}.sql`])
+ const targetFolderId = generateDeterministicUuid(['target-folder'])
+
+ const createMockDirent = (name: string, isDirectory: boolean) => ({
+ name,
+ isDirectory: () => isDirectory,
+ isFile: () => !isDirectory,
+ })
+
+ mockedFS.access.mockResolvedValue(undefined)
+
+ // Mock filesystem structure with:
+ // - existing-snippet.sql in root
+ // - target-folder/ with existing-snippet.sql inside
+ mockedFS.readdir.mockImplementation((dirPath: any) => {
+ if (dirPath === MOCK_SNIPPETS_DIR) {
+ return Promise.resolve([
+ createMockDirent('existing-snippet.sql', false),
+ createMockDirent('target-folder', true),
+ ] as any)
+ } else if (dirPath === path.join(MOCK_SNIPPETS_DIR, 'target-folder')) {
+ return Promise.resolve([createMockDirent(`${snippetName}.sql`, false)] as any)
+ }
+ return Promise.resolve([])
+ })
+
+ mockedFS.readFile.mockResolvedValue('SELECT * FROM table;')
+ mockedFS.unlink.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const updates = { folder_id: targetFolderId }
+
+ await expect(updateSnippet(existingSnippetId, updates)).rejects.toThrow(
+ `Snippet named "${snippetName}" already exists in the specified folder`
+ )
+ })
+ })
+
+ describe('getFolders', () => {
+ it('should read directories from the snippets folder', async () => {
+ const mockDirents = [
+ { name: 'folder1', isDirectory: () => true, isFile: () => false },
+ { name: 'folder2', isDirectory: () => true, isFile: () => false },
+ { name: 'snippet.sql', isDirectory: () => false, isFile: () => true },
+ ]
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir
+ .mockResolvedValueOnce(mockDirents as any) // First call for getFilesystemEntries
+ .mockResolvedValueOnce([]) // folder1 contents (empty)
+ .mockResolvedValueOnce([]) // folder2 contents (empty)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const folders = await getFolders()
+
+ expect(folders).toHaveLength(2)
+ expect(folders[0].name).toBe('folder1')
+ expect(folders[1].name).toBe('folder2')
+ expect(folders[0].id).toBe(generateDeterministicUuid(['folder1']))
+ expect(folders[1].id).toBe(generateDeterministicUuid(['folder2']))
+ })
+
+ it('should return empty array when no directories exist', async () => {
+ const mockDirents = [{ name: 'snippet.sql', isDirectory: () => false, isFile: () => true }]
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue(mockDirents as any)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ const folders = await getFolders()
+
+ expect(folders).toEqual([])
+ })
+
+ it('should handle directory creation when it does not exist', async () => {
+ mockedFS.access.mockRejectedValue(new Error('Directory does not exist'))
+ mockedFS.readdir.mockResolvedValue([])
+
+ const folders = await getFolders()
+
+ expect(folders).toEqual([])
+ })
+ })
+
+ describe('createFolder', () => {
+ it('should create a new folder as an actual directory', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([]) // No existing folders
+ mockedFS.mkdir.mockResolvedValue(undefined)
+
+ const result = await createFolder('New Folder')
+
+ expect(result.id).toBe(generateDeterministicUuid(['New Folder']))
+ expect(result.name).toBe('New Folder')
+ expect(result.owner_id).toBe(1)
+ expect(mockedFS.mkdir).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'New Folder'), {
+ recursive: true,
+ })
+ })
+
+ it('should handle folder creation with special characters in name', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+ mockedFS.mkdir.mockResolvedValue(undefined)
+
+ const result = await createFolder('Folder with spaces & symbols!')
+
+ expect(result.id).toBe(generateDeterministicUuid(['Folder with spaces & symbols!']))
+ expect(result.name).toBe('Folder with spaces & symbols!')
+ expect(mockedFS.mkdir).toHaveBeenCalledWith(
+ path.join(MOCK_SNIPPETS_DIR, 'Folder with spaces & symbols!'),
+ { recursive: true }
+ )
+ })
+
+ it('should throw error when folder already exists', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'Existing Folder', isDirectory: () => true, isFile: () => false },
+ ] as any)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ await expect(createFolder('Existing Folder')).rejects.toThrow(
+ 'Folder with name Existing Folder already exists'
+ )
+ })
+
+ it('should handle mkdir errors', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+ mockedFS.mkdir.mockRejectedValue(new Error('Permission denied'))
+
+ await expect(createFolder('New Folder')).rejects.toThrow('Permission denied')
+ })
+
+ it('should create directory when snippets directory does not exist', async () => {
+ mockedFS.access.mockRejectedValue(new Error('Directory does not exist'))
+ mockedFS.readdir.mockResolvedValue([])
+ mockedFS.mkdir.mockResolvedValue(undefined)
+
+ const result = await createFolder('New Folder')
+
+ expect(result.name).toBe('New Folder')
+ expect(mockedFS.mkdir).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'New Folder'), {
+ recursive: true,
+ })
+ })
+
+ it('should reject path traversal attempts with ../', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(createFolder('../malicious-folder')).rejects.toThrow(
+ 'Invalid name: path traversal or null bytes detected'
+ )
+ })
+
+ it('should reject path traversal attempts with nested directories', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(createFolder('foo/bar/folder')).rejects.toThrow(
+ 'Invalid name: path traversal or null bytes detected'
+ )
+ })
+
+ it('should reject names with null bytes', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(createFolder('malicious\0folder')).rejects.toThrow(
+ 'Invalid name: path traversal or null bytes detected'
+ )
+ })
+
+ it('should reject absolute path attempts', async () => {
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(createFolder('/etc/malicious')).rejects.toThrow(
+ 'Invalid name: path traversal or null bytes detected'
+ )
+ })
+ })
+
+ describe('deleteFolder', () => {
+ it('should delete an existing folder directory', async () => {
+ const folderId = generateDeterministicUuid(['Delete Me'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'Delete Me', isDirectory: () => true, isFile: () => false, folderId: null },
+ { name: 'Keep Me', isDirectory: () => true, isFile: () => false, folderId: null },
+ ] as any)
+ mockedFS.rm.mockResolvedValue(undefined)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ await deleteFolder(folderId)
+
+ expect(mockedFS.rm).toHaveBeenCalledWith(path.join(MOCK_SNIPPETS_DIR, 'Delete Me'), {
+ recursive: true,
+ force: true,
+ })
+ })
+
+ it('should throw error when folder not found', async () => {
+ const nonExistentId = 'non-existent-folder-id'
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(deleteFolder(nonExistentId)).rejects.toThrow(
+ `Folder with id ${nonExistentId} not found`
+ )
+ })
+
+ it('should handle directory deletion errors gracefully', async () => {
+ const folderId = generateDeterministicUuid(['Test Folder'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'Test Folder', isDirectory: () => true, isFile: () => false, folderId: null },
+ ] as any)
+
+ const error = new Error('Permission denied') as NodeJS.ErrnoException
+ error.code = 'EACCES'
+ mockedFS.rm.mockRejectedValue(error)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ await expect(deleteFolder(folderId)).rejects.toThrow('Permission denied')
+ })
+
+ it('should throw original error when directory does not exist during deletion', async () => {
+ const folderId = generateDeterministicUuid(['Test Folder'])
+
+ mockedFS.access.mockResolvedValue(undefined)
+ mockedFS.readdir.mockResolvedValue([
+ { name: 'Test Folder', isDirectory: () => true, isFile: () => false, folderId: null },
+ ] as any)
+
+ const error = new Error('Directory not found') as NodeJS.ErrnoException
+ error.code = 'ENOENT'
+ mockedFS.rm.mockRejectedValue(error)
+ mockedFS.stat.mockResolvedValue({ birthtime: new Date('2023-01-01') } as any)
+
+ await expect(deleteFolder(folderId)).rejects.toThrow(`Folder with id ${folderId} not found`)
+ })
+
+ it('should handle case when snippets directory needs to be created first', async () => {
+ const nonExistentId = 'non-existent-folder-id'
+
+ mockedFS.access.mockRejectedValue(new Error('Directory does not exist'))
+ mockedFS.readdir.mockResolvedValue([])
+
+ await expect(deleteFolder(nonExistentId)).rejects.toThrow(
+ `Folder with id ${nonExistentId} not found`
+ )
+ })
+ })
+})
diff --git a/apps/studio/lib/api/snippets.utils.ts b/apps/studio/lib/api/snippets.utils.ts
new file mode 100644
index 00000000000..cf11f6d4d9e
--- /dev/null
+++ b/apps/studio/lib/api/snippets.utils.ts
@@ -0,0 +1,466 @@
+import fs from 'fs/promises'
+import { compact, sortBy } from 'lodash'
+import path from 'path'
+import { v4 as uuidv4 } from 'uuid'
+import { z } from 'zod'
+
+import { generateDeterministicUuid } from './snippets.browser'
+import { SNIPPETS_DIR } from './snippets.constants'
+
+type DeepPartial<T> = T extends object
+ ? {
+ [P in keyof T]?: DeepPartial<T[P]>
+ }
+ : T
+
+export const SnippetSchema = z.object({
+ id: z.string().uuid(),
+ inserted_at: z.string().default(() => new Date().toISOString()),
+ updated_at: z.string().default(() => new Date().toISOString()),
+ type: z.literal('sql'),
+ name: z.string(),
+ description: z.string().optional(),
+ favorite: z.boolean().default(false),
+ content: z.object({
+ sql: z.string(),
+ content_id: z.string(),
+ schema_version: z.literal('1.0'),
+ }),
+ visibility: z.union([
+ z.literal('user'),
+ z.literal('project'),
+ z.literal('org'),
+ z.literal('public'),
+ ]),
+ project_id: z.number().default(1),
+ folder_id: z.string().nullable().default(null),
+ owner_id: z.number().default(1),
+ owner: z
+ .object({
+ id: z.number(),
+ username: z.string(),
+ })
+ .default({ id: 1, username: 'johndoe' }),
+ updated_by: z
+ .object({
+ id: z.number(),
+ username: z.string(),
+ })
+ .default({ id: 1, username: 'johndoe' }),
+})
+
+export const FolderSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ owner_id: z.number().default(1),
+ parent_id: z.string().nullable(),
+ project_id: z.number().default(1),
+})
+
+export type Snippet = z.infer<typeof SnippetSchema>
+export type Folder = z.infer<typeof FolderSchema>
+
+export type FilesystemEntry = {
+ id: string
+ name: string
+ type: 'file' | 'folder'
+ folderId: string | null
+ content?: string // Only for files
+ createdAt: Date
+}
+
+const buildSnippet = (
+ filename: string,
+ content: string,
+ folderId: string | null,
+ createdAt: Date
+) => {
+ const snippet: Snippet = {
+ id: generateDeterministicUuid([folderId, `${filename}.sql`]),
+ inserted_at: createdAt.toISOString(),
+ updated_at: createdAt.toISOString(),
+ type: 'sql',
+ name: filename.replace('.sql', ''),
+ description: '',
+ favorite: false,
+ content: {
+ sql: content, // Default content
+ content_id: uuidv4(),
+ schema_version: '1.0',
+ },
+ visibility: 'user',
+ project_id: 1,
+ folder_id: folderId,
+ owner_id: 1,
+ owner: { id: 1, username: 'johndoe' },
+ updated_by: { id: 1, username: 'johndoe' },
+ }
+
+ return snippet
+}
+
+const buildFolder = (name: string) => {
+ const folder: Folder = {
+ id: generateDeterministicUuid([name]),
+ name: name,
+ owner_id: 1,
+ parent_id: null,
+ project_id: 1,
+ }
+
+ return folder
+}
+
+const sanitizeName = (name: string): string => {
+ // Remove path traversal sequences and normalize
+ const sanitized = path.basename(name)
+ if (sanitized !== name || name.includes('\0')) {
+ throw new Error('Invalid name: path traversal or null bytes detected')
+ }
+ return sanitized
+}
+
+/**
+ * Gets a complete snapshot of the filesystem structure including files and folders
+ * @returns An array of files and folders with their metadata
+ */
+export async function getFilesystemEntries(): Promise<FilesystemEntry[]> {
+ if (SNIPPETS_DIR === '') {
+ throw new Error(
+ 'SNIPPETS_MANAGEMENT_FOLDER env var is not set. Please set it to use snippets properly.'
+ )
+ }
+
+ // Ensure the snippets directory exists
+ try {
+ await fs.access(SNIPPETS_DIR)
+ } catch {
+ await fs.mkdir(SNIPPETS_DIR, { recursive: true })
+ }
+
+ const entries: FilesystemEntry[] = []
+
+ const readEntriesRecursively = async (
+ dirPath: string,
+ folderName: string | null
+ ): Promise<void> => {
+ const items = await fs.readdir(dirPath, { withFileTypes: true })
+ const folderId = folderName ? generateDeterministicUuid([folderName]) : null
+
+ for (const item of items) {
+ const itemPath = path.join(dirPath, item.name)
+
+ if (item.isDirectory()) {
+ // if the folder entry is under another folder, skip it. Subdirectories are not supported.
+ if (folderName) {
+ continue
+ }
+
+ const stats = await fs.stat(itemPath)
+
+ // Add folder entry
+ entries.push({
+ id: generateDeterministicUuid([folderId, item.name]),
+ name: item.name,
+ type: 'folder',
+ // Folders are always at root level in this implementation
+ folderId: null,
+ createdAt: stats.birthtime,
+ })
+
+ await readEntriesRecursively(itemPath, item.name)
+ } else if (item.isFile() && item.name.endsWith('.sql')) {
+ const [content, stats] = await Promise.all([
+ fs.readFile(itemPath, 'utf-8'),
+ fs.stat(itemPath),
+ ])
+ const snippetName = item.name.replace('.sql', '')
+
+ entries.push({
+ id: generateDeterministicUuid([folderId, `${snippetName}.sql`]),
+ name: snippetName,
+ type: 'file',
+ folderId: folderId,
+ content: content,
+ createdAt: stats.birthtime,
+ })
+ }
+ }
+ }
+
+ await readEntriesRecursively(SNIPPETS_DIR, null)
+ return entries
+}
+
+export const getSnippet = async (snippetId: string) => {
+ const entries = await getFilesystemEntries()
+ const foundSnippet = entries.find((e) => e.type === 'file' && e.id === snippetId)
+
+ if (!foundSnippet) {
+ throw new Error(`Snippet with id ${snippetId} not found`)
+ }
+
+ return buildSnippet(
+ foundSnippet.name,
+ foundSnippet.content || '',
+ foundSnippet.folderId,
+ foundSnippet.createdAt
+ )
+}
+
+/**
+ * Gets a filtered paginated list of snippets based on the provided criteria
+ */
+export const getSnippets = async ({
+ searchTerm,
+ limit,
+ cursor,
+ sort,
+ sortOrder,
+ folderId,
+}: {
+ searchTerm?: string
+ limit?: number
+ cursor?: string
+ sortOrder?: 'asc' | 'desc'
+ sort?: 'name' | 'inserted_at'
+ folderId?: string | null
+}): Promise<{ cursor: string | undefined; snippets: Snippet[] }> => {
+ // Normalize and set default values
+ const normalizedSearchTerm = searchTerm?.trim() ?? ''
+ const normalizedLimit = limit ?? 100
+ const normalizedSort = sort ?? 'inserted_at'
+ const normalizedSortOrder = sortOrder ?? 'desc'
+ const normalizedCursor = cursor ?? undefined
+ const normalizedFolderId = folderId ?? null
+
+ // Validate inputs
+ if (normalizedLimit <= 0) {
+ throw new Error('Limit must be a positive number')
+ }
+ if (normalizedLimit > 1000) {
+ throw new Error('Limit cannot exceed 1000')
+ }
+
+ const entries = await getFilesystemEntries()
+ const files = entries.filter(
+ (entry): entry is FilesystemEntry & { type: 'file'; content: string } =>
+ entry.type === 'file' && entry.content !== undefined && entry.content !== null
+ )
+
+ // Filter snippets based on search term or folder
+ let filteredSnippets = files
+ if (normalizedSearchTerm) {
+ // When searching, look across all folders and support case-insensitive search
+ filteredSnippets = files.filter((file) =>
+ file.name.toLowerCase().includes(normalizedSearchTerm.toLowerCase())
+ )
+ } else {
+ // Filter by specific folder or root (null)
+ filteredSnippets = files.filter((file) => file.folderId === normalizedFolderId)
+ }
+
+ // Sort snippets
+ const sortedSnippets = sortBy(filteredSnippets, (snippet) => {
+ if (normalizedSort === 'inserted_at') {
+ return snippet.createdAt.getTime()
+ }
+ return snippet.name.toLowerCase() // Case-insensitive name sorting
+ })
+
+ if (normalizedSortOrder === 'desc') {
+ sortedSnippets.reverse()
+ }
+
+ // Apply cursor-based pagination
+ let paginatedSnippets = sortedSnippets
+ if (normalizedCursor) {
+ const cursorIndex = sortedSnippets.findIndex((s) => s.id === normalizedCursor)
+ if (cursorIndex !== -1) {
+ paginatedSnippets = sortedSnippets.slice(cursorIndex + 1)
+ }
+ // If cursor not found, return all snippets (graceful degradation)
+ }
+
+ // Apply limit and determine next cursor
+ let nextCursor: string | undefined = undefined
+ let finalSnippets = paginatedSnippets
+
+ if (normalizedLimit && paginatedSnippets.length > normalizedLimit) {
+ finalSnippets = paginatedSnippets.slice(0, normalizedLimit)
+ nextCursor = finalSnippets[finalSnippets.length - 1].id
+ }
+
+ return {
+ cursor: nextCursor,
+ snippets: finalSnippets.map((file) =>
+ buildSnippet(file.name, file.content, file.folderId, file.createdAt)
+ ),
+ }
+}
+
+/**
+ * Saves a snippet to the filesystem
+ */
+export async function saveSnippet(snippet: Snippet): Promise<Snippet> {
+ const entries = await getFilesystemEntries()
+ const existingSnippet = entries.find((entry) => entry.id === snippet.id && entry.type === 'file')
+
+ if (existingSnippet) {
+ throw new Error(`Snippet with id ${snippet.id} already exists`)
+ }
+
+ // check if the folder exists
+ if (snippet.folder_id !== null) {
+ const existingFolder = entries.find(
+ (entry) => entry.id === snippet.folder_id && entry.type === 'folder'
+ )
+ if (existingFolder === undefined) {
+ throw new Error(`Folder with id ${snippet.folder_id} not found`)
+ }
+ }
+
+ const snippetName = sanitizeName(snippet.name)
+ const content = snippet.content.sql || ''
+ const folderId = snippet.folder_id || null
+ const folder = entries.find((f) => f.id === folderId && f.type === 'folder')
+
+ const folderPath = folder ? path.join(SNIPPETS_DIR, folder.name) : SNIPPETS_DIR
+ const filePath = path.join(folderPath, `${snippetName}.sql`)
+ await fs.writeFile(filePath, content || '', 'utf-8')
+ const stats = await fs.stat(filePath)
+
+ const result = buildSnippet(snippetName, content, snippet.folder_id, stats.birthtime)
+ return result
+}
+
+/**
+ * Deletes a snippet from the filesystem
+ */
+export async function deleteSnippet(id: string): Promise<void> {
+ const entries = await getFilesystemEntries()
+ const found = entries.find((entry) => entry.id === id && entry.type === 'file')
+
+ if (!found) {
+ throw new Error(`Snippet with id ${id} not found`)
+ }
+
+ const filename = `${found.name}.sql`
+ const currentFolder = entries.find((f) => f.id === found.folderId && f.type === 'folder')
+ const paths = compact([SNIPPETS_DIR, currentFolder?.name, filename])
+ const filePath = path.join(...paths)
+
+ try {
+ await fs.unlink(filePath)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ throw error
+ }
+ }
+}
+
+/**
+ * Updates a snippet in the filesystem. It also handles renaming and moving.
+ */
+export async function updateSnippet(id: string, updates: DeepPartial<Snippet>): Promise<Snippet> {
+ const entries = await getFilesystemEntries()
+ const foundSnippet = entries
+ .filter(
+ (entry): entry is FilesystemEntry & { type: 'file'; content: string } => entry.type === 'file'
+ )
+ .find((s) => s.id === id)
+
+ if (!foundSnippet) {
+ throw new Error(`Snippet with id ${id} not found`)
+ }
+
+ const newId = generateDeterministicUuid([
+ updates.folder_id !== undefined ? updates.folder_id : foundSnippet.folderId,
+ `${updates.name ?? foundSnippet.name}.sql`,
+ ])
+
+ const snippetAtTargetLocation = entries.find(
+ (entry) => entry.id === newId && entry.type === 'file'
+ )
+
+ if (snippetAtTargetLocation && snippetAtTargetLocation.id !== foundSnippet.id) {
+ throw new Error(
+ `Snippet named "${updates.name ?? foundSnippet.name}" already exists in the specified folder`
+ )
+ }
+
+ const snippet = buildSnippet(
+ foundSnippet.name,
+ foundSnippet.content || '',
+ foundSnippet.folderId,
+ foundSnippet.createdAt
+ )
+
+ // it's easier to delete the old file first and then recreate a new one
+ await deleteSnippet(snippet.id)
+
+ const updatedSnippet = await saveSnippet({
+ name: updates.name ?? snippet.name,
+ content: updates.content ?? snippet.content,
+ // folder_id can be null
+ folder_id: updates.folder_id !== undefined ? updates.folder_id : snippet.folder_id,
+ } as Snippet)
+
+ return updatedSnippet
+}
+
+export const getFolders = async (folderId: string | null = null): Promise<Folder[]> => {
+ const entries = await getFilesystemEntries()
+ const folders = entries
+ .filter(
+ (entry): entry is FilesystemEntry & { type: 'folder' } =>
+ entry.type === 'folder' && entry.folderId === folderId
+ )
+ .map((folder) => buildFolder(folder.name))
+ return folders
+}
+
+/**
+ * Creates a new folder as an actual directory
+ */
+export async function createFolder(_folderName: string): Promise<Folder> {
+ const folderName = sanitizeName(_folderName)
+
+ const entries = await getFilesystemEntries()
+ const existingFolder = entries.find((folder) => folder.name === folderName)
+
+ if (existingFolder) {
+ throw new Error(`Folder with name ${folderName} already exists`)
+ }
+
+ const folderPath = path.join(SNIPPETS_DIR, folderName)
+
+ await fs.mkdir(folderPath, { recursive: true })
+ const newFolder = buildFolder(folderName)
+
+ return newFolder
+}
+
+/**
+ * Deletes a folder directory from the filesystem
+ * @throws {Error} If the folder doesn't exist
+ */
+export async function deleteFolder(id: string): Promise<void> {
+ const entries = await getFilesystemEntries()
+ const folder = entries.find((f) => f.id === id && f.type === 'folder')
+
+ if (!folder) {
+ throw new Error(`Folder with id ${id} not found`)
+ }
+
+ const folderPath = path.join(SNIPPETS_DIR, folder.name)
+ try {
+ await fs.rm(folderPath, { recursive: true, force: true })
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ throw error
+ }
+ // If folder doesn't exist, still throw the original error
+ throw new Error(`Folder with id ${id} not found`)
+ }
+}
diff --git a/apps/studio/pages/api/platform/projects/[ref]/content/count.ts b/apps/studio/pages/api/platform/projects/[ref]/content/count.ts
index 875d4c1f8ab..de5fcaee2fe 100644
--- a/apps/studio/pages/api/platform/projects/[ref]/content/count.ts
+++ b/apps/studio/pages/api/platform/projects/[ref]/content/count.ts
@@ -1,8 +1,10 @@
import { paths } from 'api-types'
-import apiWrapper from 'lib/api/apiWrapper'
import { NextApiRequest, NextApiResponse } from 'next'
-export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+import apiWrapper from 'lib/api/apiWrapper'
+import { getSnippets } from 'lib/api/snippets.utils'
+
+const wrappedHandler = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
async function handler(req: NextApiRequest, res: NextApiResponse) {
const { method } = req
@@ -16,9 +18,30 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
}
-type ResponseData =
- paths['/platform/projects/{ref}/content/count']['get']['responses']['200']['content']['application/json']
+type GetRequestData = paths['/platform/projects/{ref}/content/count']['get']['parameters']['query']
-const handleGetAll = async (req: NextApiRequest, res: NextApiResponse<ResponseData>) => {
- return res.status(200).json({ shared: 0, favorites: 0, private: 1 })
+const handleGetAll = async (req: NextApiRequest, res: NextApiResponse) => {
+ const params = req.query as GetRequestData
+
+ try {
+ const { snippets } = await getSnippets({
+ searchTerm: params?.name,
+ })
+ if (params?.name) {
+ return res.status(200).json({
+ count: snippets.length,
+ })
+ } else {
+ return res.status(200).json({
+ shared: snippets.filter((s) => s.visibility === 'project').length,
+ favorites: snippets.filter((s) => s.favorite).length,
+ private: snippets.filter((s) => s.visibility === 'user').length,
+ })
+ }
+ } catch (error: any) {
+ console.error('Error fetching snippets:', error)
+ return res.status(500).json({ message: error?.message ?? 'Failed to get count' })
+ }
}
+
+export default wrappedHandler
diff --git a/apps/studio/pages/api/platform/projects/[ref]/content/folders/[id].ts b/apps/studio/pages/api/platform/projects/[ref]/content/folders/[id].ts
index 15f13a84824..1cf59d106db 100644
--- a/apps/studio/pages/api/platform/projects/[ref]/content/folders/[id].ts
+++ b/apps/studio/pages/api/platform/projects/[ref]/content/folders/[id].ts
@@ -1,8 +1,10 @@
import { paths } from 'api-types'
-import apiWrapper from 'lib/api/apiWrapper'
import { NextApiRequest, NextApiResponse } from 'next'
-export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+import apiWrapper from 'lib/api/apiWrapper'
+import { getFolders, getSnippets } from 'lib/api/snippets.utils'
+
+const wrappedHandler = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
async function handler(req: NextApiRequest, res: NextApiResponse) {
const { method } = req
@@ -18,11 +20,26 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
}
+type GetRequestData =
+ paths['/platform/projects/{ref}/content/folders/{id}']['get']['parameters']['query']
type GetResponseData =
paths['/platform/projects/{ref}/content/folders/{id}']['get']['responses']['200']['content']['application/json']
const handleGetAll = async (req: NextApiRequest, res: NextApiResponse<GetResponseData>) => {
- return res.status(200).json({ data: { folders: [], contents: [] } })
+ const params = req.query as GetRequestData
+ const folderId = (req.query.id as string) ?? null
+
+ const folders = await getFolders(folderId)
+ const { cursor, snippets } = await getSnippets({
+ searchTerm: params?.name,
+ cursor: params?.cursor,
+ folderId: folderId,
+ limit: params?.limit ? Number(params.limit) : undefined,
+ sort: params?.sort_by,
+ sortOrder: params?.sort_order,
+ })
+
+ return res.status(200).json({ data: { folders: folders, contents: snippets }, cursor })
}
type PatchResponseData =
@@ -32,3 +49,5 @@ const handlePatch = async (req: NextApiRequest, res: NextApiResponse<PatchRespon
// Platform specific endpoint
return res.status(200).json({} as never)
}
+
+export default wrappedHandler
diff --git a/apps/studio/pages/api/platform/projects/[ref]/content/folders/index.ts b/apps/studio/pages/api/platform/projects/[ref]/content/folders/index.ts
index 7720c8eca7e..e9c0143eda2 100644
--- a/apps/studio/pages/api/platform/projects/[ref]/content/folders/index.ts
+++ b/apps/studio/pages/api/platform/projects/[ref]/content/folders/index.ts
@@ -1,8 +1,10 @@
import { paths } from 'api-types'
-import apiWrapper from 'lib/api/apiWrapper'
import { NextApiRequest, NextApiResponse } from 'next'
-export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+import apiWrapper from 'lib/api/apiWrapper'
+import { createFolder, deleteFolder, getFolders, getSnippets } from 'lib/api/snippets.utils'
+
+const wrappedHandler = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
async function handler(req: NextApiRequest, res: NextApiResponse) {
const { method } = req
@@ -20,46 +22,50 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
}
+type GetRequestData =
+ paths['/platform/projects/{ref}/content/folders']['get']['parameters']['query']
type GetResponseData =
paths['/platform/projects/{ref}/content/folders']['get']['responses']['200']['content']['application/json']
const handleGetAll = async (req: NextApiRequest, res: NextApiResponse<GetResponseData>) => {
- // Platform specific endpoint
- const snippets = [
- {
- id: '1',
- owner_id: 1,
- name: 'SQL Query',
- description: '',
- type: 'sql' as const,
- visibility: 'user' as const,
- content: {
- content_id: '1.0',
- sql: `select * from
- (select version()) as version,
- (select current_setting('server_version_num')) as version_number;`,
- schema_version: '1',
- },
- inserted_at: '',
- updated_at: '',
- project_id: 0,
- favorite: false,
- },
- ]
- return res.status(200).json({
- data: {
- folders: [],
- contents: snippets,
- },
+ const params = req.query as GetRequestData
+
+ const folders = await getFolders()
+ const { cursor, snippets } = await getSnippets({
+ searchTerm: params?.name,
+ limit: params?.limit ? Number(params.limit) : undefined,
+ cursor: params?.cursor,
+ sort: params?.sort_by,
+ sortOrder: params?.sort_order,
})
+
+ res.status(200).json({ data: { folders, contents: snippets }, cursor })
}
-const handlePost = async (req: NextApiRequest, res: NextApiResponse) => {
- // Platform specific endpoint
- return res.status(200).json({})
+type PostResponseData =
+ paths['/platform/projects/{ref}/content/folders']['post']['responses']['201']['content']['application/json']
+
+type PostRequestData =
+ paths['/platform/projects/{ref}/content/folders']['post']['requestBody']['content']['application/json']
+const handlePost = async (req: NextApiRequest, res: NextApiResponse<PostResponseData>) => {
+ const { name } = req.body as PostRequestData
+
+ const folder = await createFolder(name)
+
+ return res.status(201).json(folder)
}
const handleDelete = async (req: NextApiRequest, res: NextApiResponse) => {
- // Platform specific endpoint
+ const { ids } = req.query
+
+ if (!ids || typeof ids !== 'string') {
+ return res.status(400).json({ error: 'Folder IDs are required' })
+ }
+ const folderIds = ids.split(',').map((id) => id.trim())
+
+ await Promise.all(folderIds.map((id) => deleteFolder(id)))
+
return res.status(200).json({})
}
+
+export default wrappedHandler
diff --git a/apps/studio/pages/api/platform/projects/[ref]/content/index.ts b/apps/studio/pages/api/platform/projects/[ref]/content/index.ts
index 1d2eee7807e..ac768824f2c 100644
--- a/apps/studio/pages/api/platform/projects/[ref]/content/index.ts
+++ b/apps/studio/pages/api/platform/projects/[ref]/content/index.ts
@@ -1,9 +1,18 @@
import { paths } from 'api-types'
-import apiWrapper from 'lib/api/apiWrapper'
+import { compact } from 'lodash'
import { NextApiRequest, NextApiResponse } from 'next'
-import type { UserContent } from 'types'
+import { z } from 'zod'
+
+import apiWrapper from 'lib/api/apiWrapper'
+import {
+ deleteSnippet,
+ getSnippets,
+ saveSnippet,
+ SnippetSchema,
+ updateSnippet,
+} from 'lib/api/snippets.utils'
-export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+const wrappedHandler = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
async function handler(req: NextApiRequest, res: NextApiResponse) {
const { method } = req
@@ -11,72 +20,116 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
switch (method) {
case 'GET':
return handleGetAll(req, res)
- case 'POST':
- return handlePost(req, res)
- case 'PATCH':
- return handlePatch(req, res)
case 'PUT':
return handlePut(req, res)
+
+ case 'DELETE':
+ return handleDelete(req, res)
default:
- res.setHeader('Allow', ['GET', 'POST', 'PATCH', 'PUT'])
+ res.setHeader('Allow', ['GET', 'PUT', 'DELETE'])
res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
}
}
+type GetRequestData = paths['/platform/projects/{ref}/content']['get']['parameters']['query']
type GetResponseData =
paths['/platform/projects/{ref}/content']['get']['responses']['200']['content']['application/json']
+const getRequestParamsSchema = z.object({
+ visibility: z.enum(['project', 'user']).optional(),
+ name: z.string().optional(),
+ limit: z
+ .string()
+ .transform((val) => Number(val))
+ .pipe(z.number().int().positive())
+ .optional(),
+ cursor: z.string().optional(),
+ sort_by: z.enum(['name', 'inserted_at']).optional(),
+ sort_order: z.enum(['asc', 'desc']).optional(),
+})
+
const handleGetAll = async (req: NextApiRequest, res: NextApiResponse<GetResponseData>) => {
+ const result = getRequestParamsSchema.safeParse(req.query)
+
+ if (!result.success) {
+ return res.status(400).json({ data: [] })
+ }
+
+ const params = result.data
+
// Platform specific endpoint
- const { favorite, visibility } = req.query
- if (favorite || visibility === 'project') {
+ if (params.visibility === 'project') {
return res.status(200).json({ data: [] })
}
- const snippets = [
- {
- id: '1',
- owner_id: 1,
- name: 'SQL Query',
- description: '',
- type: 'sql' as const,
- visibility: 'user' as const,
- content: {
- content_id: '1.0',
- sql: `select * from
- (select version()) as version,
- (select current_setting('server_version_num')) as version_number;`,
- schema_version: '1',
- } as any,
- favorite: false,
- inserted_at: '',
- project_id: 0,
- updated_at: '',
- owner: {
- id: 1,
- username: 'default',
- },
- updated_by: {
- id: 1,
- username: 'default',
- },
- },
- ]
- return res.status(200).json({ data: snippets })
-}
+ try {
+ const { cursor, snippets } = await getSnippets({
+ searchTerm: params.name,
+ limit: params.limit,
+ cursor: params.cursor,
+ sort: params.sort_by,
+ sortOrder: params.sort_order,
+ })
-const handlePost = async (req: NextApiRequest, res: NextApiResponse) => {
- // Platform specific endpoint
- return res.status(200).json({})
+ return res.status(200).json({ data: snippets, cursor })
+ } catch (error) {
+ console.error('Error fetching snippets:', error)
+ return res.status(500).json({ data: [] })
+ }
}
-const handlePatch = async (req: NextApiRequest, res: NextApiResponse) => {
- // Platform specific endpoint
- return res.status(200).json({})
+const handlePut = async (req: NextApiRequest, res: NextApiResponse) => {
+ try {
+ const updates = req.body
+ const updatedSnippet = await updateSnippet(updates.id, updates)
+ return res.status(200).json(updatedSnippet)
+ } catch (error: any) {
+ if (error instanceof Error && error.message.includes('not found')) {
+ const body = req.body
+ const { data, error: parseError } = SnippetSchema.safeParse(body)
+
+ if (parseError) {
+ console.error('Validation error:', parseError)
+ return res.status(400).json({ error: parseError.message })
+ }
+
+ try {
+ const savedSnippet = await saveSnippet(data)
+ return res.status(200).json(savedSnippet)
+ } catch (error) {
+ console.error('Error creating snippet:', error)
+ return res.status(500).json({ error: 'Failed to create snippet' })
+ }
+ }
+ return res.status(500).json({ error: error?.message ?? 'Failed to update snippet' })
+ }
}
-const handlePut = async (req: NextApiRequest, res: NextApiResponse) => {
- // Platform specific endpoint
- const snippet: UserContent = req.body
- return res.status(200).json({ data: snippet })
+const snippetIdsSchema = z
+ .string()
+ .transform((val) => compact(val.split(',').map((id) => id.trim())))
+ .pipe(z.array(z.string().uuid()).nonempty())
+
+const handleDelete = async (req: NextApiRequest, res: NextApiResponse) => {
+ const { ids } = req.query
+
+ const result = snippetIdsSchema.safeParse(ids)
+ if (!result.success) {
+ return res.status(400).json({ error: 'Snippet IDs are required' })
+ }
+
+ const snippetIds = result.data
+
+ try {
+ for (const id of snippetIds) {
+ await deleteSnippet(id)
+ }
+ res.setHeader('Content-Type', 'application/json')
+ return res.status(200).send(snippetIds.map((id) => ({ id })))
+ } catch (error) {
+ console.error('Error deleting snippets:', error)
+ return res.status(500).json({ error: 'Failed to delete snippets' })
+ }
}
+
+export default wrappedHandler
diff --git a/apps/studio/pages/api/platform/projects/[ref]/content/item/[id].ts b/apps/studio/pages/api/platform/projects/[ref]/content/item/[id].ts
index ee05926344b..42065cacfeb 100644
--- a/apps/studio/pages/api/platform/projects/[ref]/content/item/[id].ts
+++ b/apps/studio/pages/api/platform/projects/[ref]/content/item/[id].ts
@@ -1,9 +1,9 @@
-import { paths } from 'api-types'
-import apiWrapper from 'lib/api/apiWrapper'
import { NextApiRequest, NextApiResponse } from 'next'
-import type { UserContent } from 'types'
-export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+import apiWrapper from 'lib/api/apiWrapper'
+import { getSnippet } from 'lib/api/snippets.utils'
+
+const wrappedHandler = (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
async function handler(req: NextApiRequest, res: NextApiResponse) {
const { method } = req
@@ -11,60 +11,23 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
switch (method) {
case 'GET':
return handleGetAll(req, res)
- case 'POST':
- return handlePost(req, res)
- case 'PATCH':
- return handlePatch(req, res)
- case 'PUT':
- return handlePut(req, res)
default:
- res.setHeader('Allow', ['GET', 'POST', 'PATCH', 'PUT'])
+ res.setHeader('Allow', ['GET'])
res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
}
}
-type ResponseData =
- paths['/platform/projects/{ref}/content/item/{id}']['get']['responses']['200']['content']['application/json']
+const handleGetAll = async (req: NextApiRequest, res: NextApiResponse) => {
+ try {
+ const snippet = await getSnippet(req.query.id as string)
-const handleGetAll = async (req: NextApiRequest, res: NextApiResponse<ResponseData>) => {
- // Platform specific endpoint
- const snippet = {
- id: '1',
- owner_id: 1,
- name: 'SQL Query',
- description: '',
- type: 'sql' as const,
- visibility: 'user' as const,
- content: {
- content_id: '1.0',
- sql: `select * from
- (select version()) as version,
- (select current_setting('server_version_num')) as version_number;`,
- schema_version: '1',
- } as any,
- favorite: false,
- inserted_at: '',
- project_id: 0,
- updated_at: '',
+ return res.status(200).json(snippet)
+ } catch (error) {
+ if (error instanceof Error && error.message.includes('not found')) {
+ return res.status(404).json({ message: 'Content not found.' })
+ }
+ return res.status(500).json({ data: null, error: { message: 'Internal Server Error' } })
}
-
- return res.status(200).json({
- ...snippet,
- })
}
-const handlePost = async (req: NextApiRequest, res: NextApiResponse) => {
- // Platform specific endpoint
- return res.status(200).json({})
-}
-
-const handlePatch = async (req: NextApiRequest, res: NextApiResponse) => {
- // Platform specific endpoint
- return res.status(200).json({})
-}
-
-const handlePut = async (req: NextApiRequest, res: NextApiResponse) => {
- // Platform specific endpoint
- const snippet: UserContent = req.body
- return res.status(200).json({ data: snippet })
-}
+export default wrappedHandler
diff --git a/apps/studio/state/sql-editor-v2.ts b/apps/studio/state/sql-editor-v2.ts
index be0fe276f79..671153c60c6 100644
--- a/apps/studio/state/sql-editor-v2.ts
+++ b/apps/studio/state/sql-editor-v2.ts
@@ -144,19 +144,17 @@ export const sqlEditorState = proxy({
if (snippet) {
snippet.name = name
snippet.description = description
-
- sqlEditorState.needsSaving.set(id, true)
}
},
- removeSnippet: (id: string) => {
+ removeSnippet: (id: string, skipSave: boolean = false) => {
const { [id]: snippet, ...otherSnippets } = sqlEditorState.snippets
sqlEditorState.snippets = otherSnippets
const { [id]: result, ...otherResults } = sqlEditorState.results
sqlEditorState.results = otherResults
- sqlEditorState.needsSaving.delete(id)
+ if (!skipSave) sqlEditorState.needsSaving.delete(id)
},
addFolder: ({ projectRef, folder }: { projectRef: string; folder: SnippetFolder }) => {
diff --git a/scripts/generateLocalEnv.js b/scripts/generateLocalEnv.js
index 5aa2cb88408..b6fb6bd79ac 100644
--- a/scripts/generateLocalEnv.js
+++ b/scripts/generateLocalEnv.js
@@ -30,6 +30,7 @@ const defaultEnv = {
NEXT_PUBLIC_GOTRUE_URL: '$SUPABASE_PUBLIC_URL/auth/v1',
NEXT_PUBLIC_HCAPTCHA_SITE_KEY: '10000000-ffff-ffff-ffff-000000000001',
NEXT_PUBLIC_NODE_ENV: 'test',
+ SNIPPETS_MANAGEMENT_FOLDER: '../../supabase/snippets',
}
const environment = { ...generatedEnv, ...defaultEnv }
diff --git a/supabase/.gitignore b/supabase/.gitignore
index 773c7c3e0a1..d2823625dc4 100644
--- a/supabase/.gitignore
+++ b/supabase/.gitignore
@@ -1,3 +1,5 @@
# Supabase
.branches
.temp
+snippets/*
+!snippets/seed
\ No newline at end of file
diff --git a/turbo.json b/turbo.json
index 8cb394fc1ba..eabf2b1f0ad 100644
--- a/turbo.json
+++ b/turbo.json
@@ -127,10 +127,14 @@
"AI_PRO_MODEL",
"AI_NORMAL_MODEL",
"SUPPORT_SUPABASE_SECRET_KEY",
- "STATUSPAGE_API_KEY",
- "STATUSPAGE_PAGE_ID"
+ "STATUSPAGE_API_KEY",
+ "STATUSPAGE_PAGE_ID"
+ ],
+ "passThroughEnv": [
+ "CURRENT_CLI_VERSION",
+ "VERCEL_GIT_COMMIT_SHA",
+ "SNIPPETS_MANAGEMENT_FOLDER"
],
- "passThroughEnv": ["CURRENT_CLI_VERSION", "VERCEL_GIT_COMMIT_SHA"],
"outputs": [".next/**", "!.next/cache/**"]
},
"www#build": {