The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: Refactor the generation of ids for snippets (#41264)
Ivan Vasilov5fb5acc0b91a
diff --git a/apps/studio/components/interfaces/HomeNew/CustomReportSection.tsx b/apps/studio/components/interfaces/HomeNew/CustomReportSection.tsxindex 76020010800..75aa631a02f 100644--- a/apps/studio/components/interfaces/HomeNew/CustomReportSection.tsx+++ b/apps/studio/components/interfaces/HomeNew/CustomReportSection.tsx@@ -308,14 +308,12 @@ export function CustomReportSection() {const data = e.dataTransfer.getData('application/json')if (!data) return- const { label, sql, config } = JSON.parse(data)+ const { label, sql } = JSON.parse(data)if (!label || !sql) returnconst toastId = toast.loading(`Creating new query: ${label}`)- const id = uuidv4()const payload = createSqlSnippetSkeletonV2({- id,name: label,sql,owner_id: profile.id,@@ -326,7 +324,7 @@ export function CustomReportSection() {// Handle success optimisticallytoast.success(`Successfully created new query: ${label}`, { id: toastId })- addSnippetToReport({ id, name: label })+ addSnippetToReport({ id: payload.id, name: label })sendEvent({action: 'custom_report_assistant_sql_block_added',groups: { project: ref, organization: organization?.slug ?? 'Unknown' },diff --git a/apps/studio/components/interfaces/Reports/GridResize.tsx b/apps/studio/components/interfaces/Reports/GridResize.tsxindex 6355da82b91..1770fb7ce19 100644--- a/apps/studio/components/interfaces/Reports/GridResize.tsx+++ b/apps/studio/components/interfaces/Reports/GridResize.tsx@@ -13,7 +13,6 @@ import {import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'-import { uuidv4 } from 'lib/helpers'import { useProfile } from 'lib/profile'import type { Dashboards } from 'types'import { createSqlSnippetSkeletonV2 } from '../SQLEditor/SQLEditor.utils'@@ -93,15 +92,21 @@ export const GridResize = ({const toastId = toast.loading(`Creating new query: ${label}`)- const id = uuidv4()+ const payload = createSqlSnippetSkeletonV2({+ name: label,+ sql,+ owner_id: profile?.id,+ project_id: project?.id,+ }) as UpsertContentPayload+const updatedLayout = layout.map((x) => {const existingBlock = editableReport.layout.find((y) => x.i === y.id)if (existingBlock) {return { ...existingBlock, x: x.x, y: x.y }} else {return {- id,- attribute: `new_snippet_${id}`,+ id: payload.id,+ attribute: `new_snippet_${payload.id}`,chartConfig: { ...DEFAULT_CHART_CONFIG, ...(config ?? {}) },label,chart_type: 'bar',@@ -114,22 +119,14 @@ export const GridResize = ({})setEditableReport({ ...editableReport, layout: updatedLayout })- const payload = createSqlSnippetSkeletonV2({- id,- name: label,- sql,- owner_id: profile?.id,- project_id: project?.id,- }) as UpsertContentPayload-upsertContent({ projectRef: ref, payload },{onSuccess: () => {toast.success(`Successfully created new query: ${label}`, { id: toastId })const finalLayout = updatedLayout.map((x) => {- if (x.id === id) {- return { ...x, attribute: `snippet_${id}` }+ if (x.id === payload.id) {+ return { ...x, attribute: `snippet_${payload.id}` }} else return x})setEditableReport({ ...editableReport, layout: finalLayout })diff --git a/apps/studio/components/interfaces/Reports/Reports.tsx b/apps/studio/components/interfaces/Reports/Reports.tsxindex 84407d9684d..ee69fac5641 100644--- a/apps/studio/components/interfaces/Reports/Reports.tsx+++ b/apps/studio/components/interfaces/Reports/Reports.tsx@@ -42,7 +42,7 @@ const DEFAULT_CHART_ROW_COUNT = 1const Reports = () => {const router = useRouter()- const { id, ref } = useParams()+ const { id: reportId, ref } = useParams()const { profile } = useProfile()const { data: project } = useSelectedProjectQuery()const { data: selectedOrg } = useSelectedOrganizationQuery()@@ -78,7 +78,7 @@ const Reports = () => {})const { mutate: sendEvent } = useSendEventMutation()- const currentReport = userContents?.content.find((report) => report.id === id)+ const currentReport = userContents?.content.find((report) => report.id === reportId)const currentReportContent = currentReport?.content as Dashboards.Contentconst { can: canReadReport, isLoading: isLoadingPermissions } = useAsyncCheckPermissions(@@ -311,16 +311,22 @@ const Reports = () => {if (!label || !sql) return console.error('SQL and Label required')const toastId = toast.loading(`Creating new query: ${label}`)- const id = uuidv4()++ const payload = createSqlSnippetSkeletonV2({+ name: label,+ sql,+ owner_id: profile?.id,+ project_id: project?.id,+ }) as UpsertContentPayloadconst updatedLayout = [...config.layout]updatedLayout.push({- id,+ id: payload.id,label,x: 0,y: 0,chart_type: 'bar',- attribute: `new_snippet_${id}` as Dashboards.ChartType,+ attribute: `new_snippet_${payload.id}` as Dashboards.ChartType,w: DEFAULT_CHART_COLUMN_COUNT,h: DEFAULT_CHART_ROW_COUNT,chartConfig: { ...DEFAULT_CHART_CONFIG, ...(sqlConfig ?? {}) },@@ -329,22 +335,14 @@ const Reports = () => {setConfig({ ...config, layout: [...updatedLayout] })- const payload = createSqlSnippetSkeletonV2({- id,- name: label,- sql,- owner_id: profile?.id,- project_id: project?.id,- }) as UpsertContentPayload-upsertContent({ projectRef: ref, payload },{onSuccess: () => {toast.success(`Successfully created new query: ${label}`, { id: toastId })const finalLayout = updatedLayout.map((x) => {- if (x.id === id) {- return { ...x, attribute: `snippet_${id}` as Dashboards.ChartType }+ if (x.id === payload.id) {+ return { ...x, attribute: `snippet_${payload.id}` as Dashboards.ChartType }} else return x})setConfig({ ...config, layout: finalLayout })diff --git a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsxindex 11dcc2e67a1..7ba06a2e053 100644--- a/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx@@ -14,12 +14,12 @@ import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { useTabsStateSnapshot } from 'state/tabs'import { cn } from 'ui'import { Admonition } from 'ui-patterns'-import { untitledSnippetTitle } from './SQLEditor.constants'import type { IStandaloneCodeEditor } from './SQLEditor.types'import { createSqlSnippetSkeletonV2 } from './SQLEditor.utils'export type MonacoEditorProps = {id: string+ snippetName: stringclassName?: stringeditorRef: MutableRefObject<IStandaloneCodeEditor | null>monacoRef: MutableRefObject<Monaco | null>@@ -39,6 +39,7 @@ export type MonacoEditorProps = {const MonacoEditor = ({id,+ snippetName,editorRef,monacoRef,autoFocus = true,@@ -187,12 +188,10 @@ const MonacoEditor = ({function handleEditorChange(value: string | undefined) {tabsSnap.makeActiveTabPermanent()if (id && value) {- if (!!snippet) {- setValue(value)- } else if (ref && !!profile && !!project) {+ if (ref && profile !== undefined && project !== undefined) {const snippet = createSqlSnippetSkeletonV2({- id,- name: untitledSnippetTitle,+ idOverride: id,+ name: snippetName,sql: value,owner_id: profile?.id,project_id: project?.id,@@ -200,6 +199,7 @@ const MonacoEditor = ({snapV2.addSnippet({ projectRef: ref, snippet })router.push(`/project/${ref}/sql/${snippet.id}`, undefined, { shallow: true })}+ setValue(value)}}diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.constants.tsindex 4c52b23d7bf..09ba0e4fb7b 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts@@ -1,3 +1,4 @@+import { IS_PLATFORM } from 'common'import type { SqlSnippets, UserContent } from 'types'const SQL_SNIPPET_SCHEMA_VERSION = '1.0'@@ -20,8 +21,20 @@ export const sqlAiDisclaimerComment = `-- Always verify the output before executing`.trim()+// Should only be used for comparisons. If you need a new title, use generateSnippetTitle()export const untitledSnippetTitle = 'Untitled query'+/**+ * Generates a snippet title. If the platform is self-hosted, it will return a random number to avoid conflicts.+ */+export const generateSnippetTitle = () => {+ if (IS_PLATFORM) {+ return untitledSnippetTitle+ } else {+ return `${untitledSnippetTitle} ${Math.floor(Math.random() * 900) + 100}`+ }+}+export const destructiveSqlRegex = [/^(.*;)?\s*(drop|delete|truncate|alter\s+table\s+.*\s+drop\s+column)\s/is,]diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex 441b25d5559..292d31f670a 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -22,9 +22,10 @@ import { useOrgAiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'import { useSchemasForAi } from 'hooks/misc/useSchemasForAi'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'+import { generateUuid } from 'lib/api/snippets.browser'import { BASE_PATH } from 'lib/constants'import { formatSql } from 'lib/formatSql'-import { detectOS, uuidv4 } from 'lib/helpers'+import { detectOS } from 'lib/helpers'import { useProfile } from 'lib/profile'import { wrapWithRoleImpersonation } from 'lib/role-impersonation'import { useAiAssistantStateSnapshot } from 'state/ai-assistant-state'@@ -54,6 +55,7 @@ import {import { useSqlEditorDiff, useSqlEditorPrompt } from './hooks'import { RunQueryWarningModal } from './RunQueryWarningModal'import {+ generateSnippetTitle,ROWS_PER_PAGE_OPTIONS,sqlAiDisclaimerComment,untitledSnippetTitle,@@ -121,10 +123,13 @@ export const SQLEditor = () => {const [queryHasUpdateWithoutWhere, setQueryHasUpdateWithoutWhere] = useState(false)const [showWidget, setShowWidget] = useState(false)- // generate an id to be used for new snippets. The dependency on urlId is to avoid a bug which+ // generate a new snippet title and an id to be used for new snippets. The dependency on urlId is to avoid a bug which// shows up when clicking on the SQL Editor while being in the SQL editor on a random snippet.- // eslint-disable-next-line react-hooks/exhaustive-deps- const generatedId = useMemo(() => uuidv4(), [urlId])+ const [generatedNewSnippetName, generatedId] = useMemo(() => {+ const name = generateSnippetTitle()+ return [name, generateUuid([name])]+ }, [urlId])+// the id is stable across renders - it depends either on the url or on the memoized generated idconst id = !urlId || urlId === 'new' ? generatedId : urlId@@ -353,7 +358,6 @@ export const SQLEditor = () => {try {const snippet = createSqlSnippetSkeletonV2({- id: uuidv4(),name,sql,owner_id: profile.id,@@ -753,6 +757,11 @@ export const SQLEditor = () => {: ''}id={id}+ snippetName={+ urlId === 'new'+ ? generatedNewSnippetName+ : snapV2.snippets[id]?.snippet.name ?? generatedNewSnippetName+ }className={cn(isDiffOpen && 'hidden')}editorRef={editorRef}monacoRef={monacoRef}diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.tsindex efc327aba41..c4661a6f14c 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts@@ -1,58 +1,34 @@+import { generateUuid } from 'lib/api/snippets.browser'import { removeCommentsFromSql } from 'lib/helpers'import type { SnippetWithContent } from 'state/sql-editor-v2'-import type { SqlSnippets, UserContent } from 'types'import {NEW_SQL_SNIPPET_SKELETON,destructiveSqlRegex,sqlAiDisclaimerComment,} from './SQLEditor.constants'-import { ContentDiff, DiffType } from './SQLEditor.types'--/**- * @deprecated- */-export const createSqlSnippetSkeleton = ({- id,- name,- sql,- owner_id,- project_id,-}: {- id?: string- name?: string- sql?: string- owner_id?: number- project_id?: number-} = {}): UserContent<SqlSnippets.Content> => {- return {- ...NEW_SQL_SNIPPET_SKELETON,- id,- ...(name && { name }),- ...(owner_id && { owner_id }),- ...(project_id && { project_id }),- content: {- ...NEW_SQL_SNIPPET_SKELETON.content,- content_id: id ?? '',- sql: sql ?? '',- },- }-}+import { ContentDiff } from './SQLEditor.types'export const createSqlSnippetSkeletonV2 = ({- id,name,sql,owner_id,project_id,folder_id,+ idOverride,}: {- id: stringname: stringsql: stringowner_id: numberproject_id: numberfolder_id?: string+ /**+ * Optionally, provide a specific snippetId to use for the snippet. This is used to ensure the snippet is created+ * with a known id, such as to prevent flicker in the SQL editor when adding new unsaved snippets.+ */+ idOverride?: string}): SnippetWithContent => {+ const id = idOverride ?? generateUuid([folder_id, name])+return {...NEW_SQL_SNIPPET_SKELETON,id,@@ -72,32 +48,6 @@ export const createSqlSnippetSkeletonV2 = ({}}-export function getDiffTypeButtonLabel(diffType: DiffType) {- switch (diffType) {- case DiffType.Modification:- return 'Accept change'- case DiffType.Addition:- return 'Accept addition'- case DiffType.NewSnippet:- return 'Create new snippet'- default:- throw new Error(`Unknown diff type '${diffType}'`)- }-}--export function getDiffTypeDropdownLabel(diffType: DiffType) {- switch (diffType) {- case DiffType.Modification:- return 'Compare as change'- case DiffType.Addition:- return 'Compare as addition'- case DiffType.NewSnippet:- return 'Compare as new snippet'- default:- throw new Error(`Unknown diff type '${diffType}'`)- }-}-export function checkDestructiveQuery(sql: string) {const cleanedSql = removeCommentsFromSql(sql)return destructiveSqlRegex.some((regex) => regex.test(cleanedSql))diff --git a/apps/studio/components/interfaces/SQLEditor/SQLTemplates/SQLQuickstarts.tsx b/apps/studio/components/interfaces/SQLEditor/SQLTemplates/SQLQuickstarts.tsxindex 5e9141c41f0..4dd977b484c 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLTemplates/SQLQuickstarts.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLTemplates/SQLQuickstarts.tsx@@ -10,7 +10,6 @@ import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'-import { uuidv4 } from 'lib/helpers'import { useProfile } from 'lib/profile'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { cn, SQL_ICON } from 'ui'@@ -48,7 +47,6 @@ const SQLQuickstarts = () => {try {const snippet = createSqlSnippetSkeletonV2({- id: uuidv4(),name,sql,owner_id: profile?.id,diff --git a/apps/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx b/apps/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsxindex e33799346e0..81a2de6c049 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx@@ -10,7 +10,6 @@ import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'-import { uuidv4 } from 'lib/helpers'import { useProfile } from 'lib/profile'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { cn, SQL_ICON } from 'ui'@@ -48,7 +47,6 @@ const SQLTemplates = () => {try {const snippet = createSqlSnippetSkeletonV2({- id: uuidv4(),name,sql,owner_id: profile?.id,diff --git a/apps/studio/components/interfaces/SQLEditor/hooks.ts b/apps/studio/components/interfaces/SQLEditor/hooks.tsindex 6d712056d34..b4f51f0d332 100644--- a/apps/studio/components/interfaces/SQLEditor/hooks.ts+++ b/apps/studio/components/interfaces/SQLEditor/hooks.ts@@ -4,9 +4,6 @@ import { useCallback, useEffect, useMemo, useState } from 'react'import { toast } from 'sonner'import { useParams } from 'common'-import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'-import { uuidv4 } from 'lib/helpers'import { useProfile } from 'lib/profile'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { ContentDiff, DiffType } from './SQLEditor.types'@@ -16,6 +13,8 @@ import {compareAsNewSnippet,createSqlSnippetSkeletonV2,} from './SQLEditor.utils'+import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'export const useNewQuery = () => {const router = useRouter()@@ -45,7 +44,6 @@ export const useNewQuery = () => {try {const snippet = createSqlSnippetSkeletonV2({- id: uuidv4(),name,sql,owner_id: profile?.id,diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsxindex a6af02d7eef..b35daf3efb5 100644--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx@@ -9,6 +9,7 @@ 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'@@ -148,10 +149,12 @@ export const SQLEditorMenu = () => {<FilePlus size={14} />Create a new snippet</DropdownMenuItem>- <DropdownMenuItem className="gap-x-2" onClick={() => createNewFolder()}>- <FolderPlus size={14} />- Create a new folder- </DropdownMenuItem>+ {IS_PLATFORM && (+ <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.tsxindex 5eab1c04aaf..a4b74c5ea79 100644--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx@@ -8,7 +8,7 @@ import { IS_PLATFORM, LOCAL_STORAGE_KEYS, useParams } from 'common'import DownloadSnippetModal from 'components/interfaces/SQLEditor/DownloadSnippetModal'import { MoveQueryModal } from 'components/interfaces/SQLEditor/MoveQueryModal'import RenameQueryModal from 'components/interfaces/SQLEditor/RenameQueryModal'-import { untitledSnippetTitle } from 'components/interfaces/SQLEditor/SQLEditor.constants'+import { generateSnippetTitle } from 'components/interfaces/SQLEditor/SQLEditor.constants'import { createSqlSnippetSkeletonV2 } from 'components/interfaces/SQLEditor/SQLEditor.utils'import { EmptyPrivateQueriesPanel } from 'components/layouts/SQLEditorLayout/PrivateSqlSnippetEmpty'import EditorMenuListSkeleton from 'components/layouts/TableEditorLayout/EditorMenuListSkeleton'@@ -20,7 +20,6 @@ import { Snippet, SnippetFolder, useSQLSnippetFoldersQuery } from 'data/content/import { useSqlSnippetsQuery } from 'data/content/sql-snippets-query'import { useLocalStorage } from 'hooks/misc/useLocalStorage'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'-import { uuidv4 } from 'lib/helpers'import { useProfile } from 'lib/profile'import { useSnippetFolders, useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { createTabId, useTabsStateSnapshot } from 'state/tabs'@@ -661,8 +660,7 @@ export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {onSelectCreate={() => {if (profile && project) {const snippet = createSqlSnippetSkeletonV2({- id: uuidv4(),- name: untitledSnippetTitle,+ name: generateSnippetTitle(),owner_id: profile?.id,project_id: project?.id,folder_id: element.id as string,diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsxindex 222bf17ac5f..e92935aae50 100644--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx@@ -25,7 +25,6 @@ import { Snippet } from 'data/content/sql-folders-query'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import useLatest from 'hooks/misc/useLatest'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'-import { uuidv4 } from 'lib/helpers'import { useProfile } from 'lib/profile'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import {@@ -204,7 +203,6 @@ export const SQLEditorTreeViewItem = ({}const snippetCopy = createSqlSnippetSkeletonV2({- id: uuidv4(),name: `${snippet.name} (Duplicate)`,sql,owner_id: profile?.id,diff --git a/apps/studio/components/layouts/Tabs/NewTab.tsx b/apps/studio/components/layouts/Tabs/NewTab.tsxindex d6fda98c921..ac75688def3 100644--- a/apps/studio/components/layouts/Tabs/NewTab.tsx+++ b/apps/studio/components/layouts/Tabs/NewTab.tsx@@ -15,16 +15,18 @@ import { QuickstartTemplatesWidget } from 'components/interfaces/TableGridEditorimport { QuickstartVariant } from 'components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/types'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { usePHFlag } from 'hooks/ui/useFlag'+import { useIsProtectedSchema } from 'hooks/useProtectedSchemas'import { uuidv4 } from 'lib/helpers'import { useProfile } from 'lib/profile'import { useTrack } from 'lib/telemetry/track'import { AssistantMessageType, useAiAssistantStateSnapshot } from 'state/ai-assistant-state'+import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { useTableEditorStateSnapshot } from 'state/table-editor'-import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'import { createTabId, useTabsStateSnapshot } from 'state/tabs'import {AiIconAnimation,@@ -37,11 +39,9 @@ import {cn,} from 'ui'import { useEditorType } from '../editors/EditorsLayout.hooks'+import { SIDEBAR_KEYS } from '../ProjectLayout/LayoutSidebar/LayoutSidebarProvider'import { ActionCard } from './ActionCard'import { RecentItems } from './RecentItems'-import { SIDEBAR_KEYS } from '../ProjectLayout/LayoutSidebar/LayoutSidebarProvider'-import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'-import { useIsProtectedSchema } from 'hooks/useProtectedSchemas'const NEW_PROJECT_THRESHOLD_DAYS = 7const TABLE_QUICKSTART_FLAG = 'tableQuickstart'@@ -202,7 +202,6 @@ export function NewTab() {try {const snippet = createSqlSnippetSkeletonV2({- id: uuidv4(),name,sql,owner_id: profile?.id,diff --git a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx b/apps/studio/components/ui/EditorPanel/EditorPanel.tsxindex 10d7a6059e3..29ae1f57d3b 100644--- a/apps/studio/components/ui/EditorPanel/EditorPanel.tsx+++ b/apps/studio/components/ui/EditorPanel/EditorPanel.tsx@@ -15,7 +15,6 @@ import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'import { BASE_PATH } from 'lib/constants'-import { uuidv4 } from 'lib/helpers'import { useProfile } from 'lib/profile'import { useEditorPanelStateSnapshot } from 'state/editor-panel-state'import { useSidebarManagerSnapshot } from 'state/sidebar-manager-state'@@ -44,6 +43,7 @@ import { containsUnknownFunction, isReadOnlySelect } from '../AIAssistantPanel/Aimport AIEditor from '../AIEditor'import { ButtonTooltip } from '../ButtonTooltip'import { SqlWarningAdmonition } from '../SqlWarningAdmonition'+import { generateSnippetTitle } from 'components/interfaces/SQLEditor/SQLEditor.constants'export const EditorPanel = () => {const {@@ -236,8 +236,7 @@ export const EditorPanel = () => {}const snippet = createSqlSnippetSkeletonV2({- id: uuidv4(),- name: 'New query',+ name: generateSnippetTitle(),sql: currentValue,owner_id: profile.id,project_id: project.id,diff --git a/apps/studio/data/content/content-upsert-mutation.ts b/apps/studio/data/content/content-upsert-mutation.tsindex 3455eb2ac40..ed510807bb4 100644--- a/apps/studio/data/content/content-upsert-mutation.ts+++ b/apps/studio/data/content/content-upsert-mutation.ts@@ -9,6 +9,7 @@ import { contentKeys } from './keys'import type { Snippet } from './sql-folders-query'export type UpsertContentPayload = Omit<components['schemas']['UpsertContentBody'], 'content'> & {+ id: stringcontent: Partial<Content['content']>favorite?: boolean}diff --git a/apps/studio/lib/api/snippets.browser.test.ts b/apps/studio/lib/api/snippets.browser.test.tsnew file mode 100644index 00000000000..8b0ff31e524--- /dev/null+++ b/apps/studio/lib/api/snippets.browser.test.ts@@ -0,0 +1,52 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { generateDeterministicUuid } from './snippets.browser'++describe('snippets.utils', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ afterEach(() => {+ vi.resetAllMocks()+ })++ describe('generateDeterministicUuid', () => {+ it('should generate the same UUID for the same input', () => {+ const input = 'test-string'+ const uuid1 = generateDeterministicUuid([input])+ const uuid2 = generateDeterministicUuid([input])++ expect(uuid1).toBe(uuid2)+ expect(uuid1).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i+ )+ })++ it('should generate different UUIDs for different inputs', () => {+ const uuid1 = generateDeterministicUuid(['input1'])+ const uuid2 = generateDeterministicUuid(['input2'])++ expect(uuid1).not.toBe(uuid2)+ })++ it('should handle empty string input', () => {+ const uuid = generateDeterministicUuid([''])+ expect(uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)+ })++ it('should handle special characters and Unicode', () => {+ const uuid1 = generateDeterministicUuid(['test-with-émojis-🚀-and-símb0ls!'])+ const uuid2 = generateDeterministicUuid(['test-with-émojis-🚀-and-símb0ls!'])+ expect(uuid1).toBe(uuid2)+ expect(uuid1).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i+ )+ })++ it('should handle very long strings', () => {+ const longString = 'a'.repeat(10000)+ const uuid = generateDeterministicUuid([longString])+ expect(uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)+ })+ })+})diff --git a/apps/studio/lib/api/snippets.browser.ts b/apps/studio/lib/api/snippets.browser.tsnew file mode 100644index 00000000000..5eaf81860a7--- /dev/null+++ b/apps/studio/lib/api/snippets.browser.ts@@ -0,0 +1,47 @@+import { IS_PLATFORM } from 'common'+import { compact } from 'lodash'+import { v4 as uuidv4 } from 'uuid'++/**+ * Generates a UUID v4. If the platform is self-hosted, it will generate a deterministic UUID v4 from the inputs.+ */+export const generateUuid = (inputs: (string | undefined | null)[] = []) => {+ const cleaned = compact(inputs)+ if (!IS_PLATFORM && cleaned.length === 0) return uuidv4()+ return IS_PLATFORM ? uuidv4() : generateDeterministicUuid(cleaned)+}++/**+ * Generates a deterministic UUID v4 from a string input+ * @param inputs - The array of strings to generate a UUID from+ * @returns A deterministic UUID v4 string+ */+export function generateDeterministicUuid(inputs: (string | undefined | null)[]): string {+ const simpleHash = (str: string): number => {+ let hash = 0+ if (str.length === 0) return hash+ for (let i = 0; i < str.length; i++) {+ const char = str.charCodeAt(i)+ hash = (hash << 5) - hash + char+ hash = hash & hash // Convert to 32-bit integer+ }+ return Math.abs(hash)+ }++ const input = compact(inputs).join('_')++ // Create a deterministic random number generator using the hash as seed+ let seed = simpleHash(input)+ const rng = () => {+ const bytes = new Uint8Array(16)+ for (let i = 0; i < 16; i++) {+ // Simple LCG (Linear Congruential Generator) for deterministic randomness+ seed = (seed * 1103515245 + 12345) & 0x7fffffff+ bytes[i] = (seed >>> 16) & 0xff+ }+ return Array.from(bytes)+ }++ // Generate UUID v4 using the deterministic RNG+ return uuidv4({ rng })+}diff --git a/apps/studio/pages/project/[ref]/sql/[id].tsx b/apps/studio/pages/project/[ref]/sql/[id].tsxindex c09873fd356..1b357e43ced 100644--- a/apps/studio/pages/project/[ref]/sql/[id].tsx+++ b/apps/studio/pages/project/[ref]/sql/[id].tsx@@ -19,6 +19,7 @@ import { createTabId, useTabsStateSnapshot } from 'state/tabs'import type { NextPageWithLayout } from 'types'import { Button } from 'ui'import { Admonition } from 'ui-patterns'+import { generateSnippetTitle } from 'components/interfaces/SQLEditor/SQLEditor.constants'const SqlEditor: NextPageWithLayout = () => {const router = useRouter()@@ -98,7 +99,7 @@ const SqlEditor: NextPageWithLayout = () => {tabs.addTab({id: tabId,type: 'sql',- label: snippet?.name || 'Untitled Query',+ label: snippet?.name || generateSnippetTitle(),metadata: {sqlId: id,name: snippet?.name,