Skip to content

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

joshenlim/fe 4204 notebooks intellisense toggle (#49300)

Joshen Lim7d28bcc26b3f
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
index 696408859c2..d772a94a77e 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
@@ -12,15 +12,18 @@ import {
verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import { acceptUntrustedSql } from '@supabase/pg-meta'
-import { useParams } from 'common'
+import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import {
+ Check,
FileText,
+ Keyboard,
Loader2,
MoreVertical,
Notebook,
NotebookText,
Play,
Save,
+ SearchX,
SquareCode,
Trash,
} from 'lucide-react'
@@ -33,6 +36,7 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
@@ -59,6 +63,7 @@ import {
} from '@/data/content/notebooks/notebook-schema'
import { useUpsertNotebookMutation } from '@/data/content/notebooks/notebook-upsert-mutation'
import { acceptUntrustedLogsSql } from '@/data/logs/safe-analytics-sql'
+import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useCurrentNotebook, useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'
import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
@@ -68,6 +73,11 @@ export const ExplorerNotebookTab = () => {
const tabs = useTabsStateSnapshot()
const snap = useNotebooksStateSnapshot()
+ const [isIntellisenseEnabled, setIsIntellisenseEnabled] = useLocalStorageQuery(
+ LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,
+ true
+ )
+
const currentNotebook = useCurrentNotebook()
const { name, content } = currentNotebook?.notebook ?? {}
const { isNotFound } = useLoadNotebook({ id, projectRef: ref })
@@ -181,9 +191,9 @@ export const ExplorerNotebookTab = () => {
if (isNotFound) {
return (
- <div className="px-20 flex flex-col h-full items-center justify-center bg-surface-100">
+ <div className="p-4 h-full bg-surface-100">
<EmptyStatePresentational
- icon={<Notebook className="text-foreground-lighter" />}
+ icon={<SearchX className="text-foreground-lighter" />}
title="Notebook not found"
description="This notebook may have been deleted or does not exist."
contentClassName="[&>h3]:text-sm [&>p]:text-xs"
@@ -231,7 +241,18 @@ export const ExplorerNotebookTab = () => {
<DropdownMenuTrigger asChild>
<ExplorerToolbarAction aria-label="More options" icon={<MoreVertical />} />
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuContent align="end" className="w-48">
+ <DropdownMenuItem
+ className="justify-between"
+ onClick={() => setIsIntellisenseEnabled(!isIntellisenseEnabled)}
+ >
+ <div className="flex items-center gap-x-2">
+ <Keyboard size={14} />
+ <span>Intellisense enabled</span>
+ </div>
+ {isIntellisenseEnabled && <Check className="text-brand" size={16} />}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
<DropdownMenuItem className="gap-x-2" onClick={() => setIsDeleteModalOpen(true)}>
<Trash size={14} />
<span>Delete notebook</span>
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
index 8ddfc51f5d8..15fd6e59fc6 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
@@ -1,3 +1,4 @@
+import { useMonaco } from '@monaco-editor/react'
import { acceptUntrustedSql, untrustedSql, type UntrustedSqlFragment } from '@supabase/pg-meta'
import { useFlag } from 'common'
import { CodeSquare, Eye, EyeOff, Play } from 'lucide-react'
@@ -34,6 +35,7 @@ import { QueryResultRenderer } from './QueryResultRenderer'
import { QuerySourceMenu } from './QuerySourceMenu'
import { useQueryEditorAi } from './useQueryEditorAi'
import { LegacyLogsRewriteBanner } from '@/components/interfaces/Settings/Logs/LegacyLogsRewriteBanner'
+import { useAddDefinitions } from '@/components/interfaces/SQLEditor/useAddDefinitions'
import { ResizableAIWidget } from '@/components/ui/AIEditor/ResizableAIWidget'
import { getEditorSelectionParts, type EditorSelection } from '@/components/ui/AIEditor/utils'
import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
@@ -173,6 +175,9 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
const dialect = query._tag === 'logs' ? 'clickhouse' : 'postgres'
const { requestCompletion, isCompletionLoading } = useQueryEditorAi({ dialect })
+ const monaco = useMonaco()
+ useAddDefinitions('', monaco, { enabled: dialect === 'postgres' })
+
const { data: databases, isPending: isLoadingDatabases } = useReadReplicasQuery(
{ projectRef: project?.ref },
{
@@ -339,15 +344,11 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
onClick={() => setShowQuery((value) => !value)}
/>
<ExplorerToolbarAction
- loading={isExecuting || isLoadingProject}
+ loading={isExecuting}
icon={<Play />}
tooltip="Run query"
disabled={
- isLoadingProject ||
- isExecuting ||
- pendingProposal !== null ||
- isRunDisabled ||
- sql.trim().length === 0
+ isBusy || pendingProposal !== null || isRunDisabled || sql.trim().length === 0
}
onClick={() => handleRunQuery()}
>
@@ -381,8 +382,13 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
placeholder={!promptState?.isOpen ? generatePlaceholder(os) : ''}
placeholderClassName="top-[13px]"
className={variant === 'embedded' ? 'h-44' : undefined}
- actions={{ runQuery: { enabled: !isRunDisabled, callback: handleRunQuery } }}
- options={{ minimap: { enabled: false }, padding: { top: 8 } }}
+ actions={{
+ runQuery: { enabled: !isRunDisabled, callback: handleRunQuery },
+ }}
+ options={{
+ minimap: { enabled: false },
+ padding: { top: 8 },
+ }}
onInputChange={(value) => onSqlChange(value ?? '')}
onMount={(editor, monaco) => {
editor.onDidBlurEditorWidget(() => onSqlCommitRef.current?.(sqlRef.current))
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
index 71425a3fb5e..389e07dcaf8 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/ExplorerNotebookTab.test.tsx
@@ -1,5 +1,6 @@
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { LOCAL_STORAGE_KEYS, safeLocalStorage } from 'common'
import { HttpResponse } from 'msw'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -87,16 +88,25 @@ beforeEach(() => {
seedNotebook([databaseCell, logCell, markdownCell])
})
-afterEach(() => notebooksState.needsSaving.clear())
+afterEach(() => {
+ notebooksState.needsSaving.clear()
+ safeLocalStorage.removeItem(LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE)
+})
describe('ExplorerNotebookTab', () => {
it('runs every database and log cell, and skips markdown cells, on "Run notebook"', async () => {
+ // `useAddDefinitions` fires its own background keywords/functions/schemas/table-columns
+ // fetches against this same generic pg-meta query endpoint (differentiated by the `key`
+ // search param) as soon as a database cell's editor mounts — those are expected and
+ // unrelated to the actual cell run.
+ const INTELLISENSE_KEYS = ['keywords', 'database-functions', 'schemas', 'table-columns']
const dbRequests: Request[] = []
addAPIMock({
method: 'post',
path: '/platform/pg-meta/:ref/query',
response: ({ request }) => {
- dbRequests.push(request)
+ const key = new URL(request.url).searchParams.get('key')
+ if (!key || !INTELLISENSE_KEYS.includes(key)) dbRequests.push(request)
return HttpResponse.json([{ result: 1 }])
},
})
@@ -130,4 +140,22 @@ describe('ExplorerNotebookTab', () => {
const runNotebookButton = await screen.findByRole('button', { name: 'Run notebook' })
expect(runNotebookButton).toBeDisabled()
})
+
+ it('toggles and persists the Intellisense enabled preference from "More options"', async () => {
+ const readPersistedValue = () => {
+ const item = safeLocalStorage.getItem(LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE)
+ return item === null ? true : (JSON.parse(item) as boolean)
+ }
+ const initialValue = readPersistedValue()
+
+ renderNotebookTab()
+
+ const moreOptionsButton = await screen.findByRole('button', { name: 'More options' })
+ await userEvent.click(moreOptionsButton)
+
+ const intellisenseItem = await screen.findByRole('menuitem', { name: 'Intellisense enabled' })
+ await userEvent.click(intellisenseItem)
+
+ await waitFor(() => expect(readPersistedValue()).toBe(!initialValue))
+ })
})
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
index 9df7654ff50..91574097064 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
@@ -130,12 +130,18 @@ describe('QueryTab execution', () => {
return HttpResponse.json<ReadReplicasData>([])
},
})
+ // `useAddDefinitions` fires its own background keywords/functions/schemas/table-columns
+ // fetches against this same generic pg-meta query endpoint (differentiated by the `key`
+ // search param) as soon as the editor mounts — those are expected and unrelated to the
+ // actual run. Only a request with no recognized intellisense `key` counts as an execution.
+ const INTELLISENSE_KEYS = ['keywords', 'database-functions', 'schemas', 'table-columns']
const requests: Request[] = []
addAPIMock({
method: 'post',
path: '/platform/pg-meta/:ref/query',
response: ({ request }) => {
- requests.push(request)
+ const key = new URL(request.url).searchParams.get('key')
+ if (!key || !INTELLISENSE_KEYS.includes(key)) requests.push(request)
return HttpResponse.json([])
},
})
diff --git a/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.ts b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.ts
new file mode 100644
index 00000000000..d398f6d010b
--- /dev/null
+++ b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.test.ts
@@ -0,0 +1,151 @@
+import { QueryClient } from '@tanstack/react-query'
+import { waitFor } from '@testing-library/react'
+import { HttpResponse } from 'msw'
+import { describe, expect, it, vi } from 'vitest'
+
+import { acquireSharedRegistration, useAddDefinitions } from './useAddDefinitions'
+import { customRenderHook } from '@/tests/lib/custom-render'
+import { addAPIMock } from '@/tests/lib/msw'
+import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'
+
+vi.mock('@/components/ui/CodeEditor/Providers/PgSQLCompletionProvider', () => ({
+ default: vi.fn((_monaco: unknown, pgInfoRef: unknown) => ({ __pgInfoRef: pgInfoRef })),
+}))
+vi.mock('@/components/ui/CodeEditor/Providers/PgSQLSignatureHelpProvider', () => ({
+ default: vi.fn((_monaco: unknown, pgInfoRef: unknown) => ({ __pgInfoRef: pgInfoRef })),
+}))
+
+describe('acquireSharedRegistration', () => {
+ it('only registers once for multiple concurrent callers sharing a key', () => {
+ const register = vi.fn(() => ({ dispose: vi.fn() }))
+
+ acquireSharedRegistration('test-key-1', register)
+ acquireSharedRegistration('test-key-1', register)
+ acquireSharedRegistration('test-key-1', register)
+
+ expect(register).toHaveBeenCalledTimes(1)
+ })
+
+ it('registers independently per key', () => {
+ const register = vi.fn(() => ({ dispose: vi.fn() }))
+
+ acquireSharedRegistration('test-key-2a', register)
+ acquireSharedRegistration('test-key-2b', register)
+
+ expect(register).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not dispose while other callers are still holding the registration', () => {
+ const dispose = vi.fn()
+ const register = vi.fn(() => ({ dispose }))
+
+ const releaseA = acquireSharedRegistration('test-key-3', register)
+ acquireSharedRegistration('test-key-3', register)
+
+ releaseA()
+
+ expect(dispose).not.toHaveBeenCalled()
+ })
+
+ it('disposes once the last caller releases', () => {
+ const dispose = vi.fn()
+ const register = vi.fn(() => ({ dispose }))
+
+ const releaseA = acquireSharedRegistration('test-key-4', register)
+ const releaseB = acquireSharedRegistration('test-key-4', register)
+
+ releaseA()
+ releaseB()
+
+ expect(dispose).toHaveBeenCalledTimes(1)
+ })
+
+ it('registers again after a full release cycle', () => {
+ const register = vi.fn(() => ({ dispose: vi.fn() }))
+
+ const release = acquireSharedRegistration('test-key-5', register)
+ release()
+ acquireSharedRegistration('test-key-5', register)
+
+ expect(register).toHaveBeenCalledTimes(2)
+ })
+
+ it('is safe to release more times than acquired', () => {
+ const dispose = vi.fn()
+ const register = vi.fn(() => ({ dispose }))
+
+ const release = acquireSharedRegistration('test-key-6', register)
+ release()
+
+ expect(() => release()).not.toThrow()
+ expect(dispose).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('useAddDefinitions', () => {
+ const createMonaco = () =>
+ ({
+ languages: {
+ registerCompletionItemProvider: vi.fn(() => ({ dispose: vi.fn() })),
+ registerSignatureHelpProvider: vi.fn(() => ({ dispose: vi.fn() })),
+ registerDocumentFormattingEditProvider: vi.fn(() => ({ dispose: vi.fn() })),
+ },
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ }) as any
+
+ it('keeps the registered provider reading fresh data after the registering editor unmounts, as long as a sibling editor is still active', async () => {
+ const getPgsqlCompletionProvider = (
+ await import('@/components/ui/CodeEditor/Providers/PgSQLCompletionProvider')
+ ).default as unknown as ReturnType<typeof vi.fn>
+
+ let keywordWords = ['select']
+ setupSqlEditorMocks()
+ addAPIMock({
+ method: 'post',
+ path: '/platform/pg-meta/:ref/query',
+ response: ({ request }) => {
+ const key = new URL(request.url).searchParams.get('key')
+ if (key === 'keywords') return HttpResponse.json(keywordWords.map((word) => ({ word })))
+ return HttpResponse.json([])
+ },
+ })
+
+ const monaco = createMonaco()
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const renderOptions = { queryClient }
+
+ // Two sibling notebook cells' editors, both mounted at once, sharing the same cache.
+ const editor1 = customRenderHook(
+ () => useAddDefinitions('', monaco, { enabled: true }),
+ renderOptions
+ )
+ const editor2 = customRenderHook(
+ () => useAddDefinitions('', monaco, { enabled: true }),
+ renderOptions
+ )
+
+ await waitFor(() =>
+ expect(monaco.languages.registerCompletionItemProvider).toHaveBeenCalledTimes(1)
+ )
+
+ // The first (and only, thanks to ref-counted registration) call registered the provider —
+ // capture the `pgInfoRef` it reads from.
+ const pgInfoRef = getPgsqlCompletionProvider.mock.calls[0][1] as {
+ current: { keywords: string[] }
+ }
+ await waitFor(() => expect(pgInfoRef.current.keywords).toEqual(['select']))
+
+ // Editor 1 — the one whose render happened to trigger the registration — closes. Editor 2
+ // is still open, so the provider must stay registered and stay current.
+ editor1.unmount()
+ expect(monaco.languages.registerCompletionItemProvider).toHaveBeenCalledTimes(1)
+
+ keywordWords = ['select', 'insert']
+ queryClient.invalidateQueries({ queryKey: ['projects', 'default', 'keywords'] })
+ editor2.rerender()
+
+ await waitFor(() => expect(pgInfoRef.current.keywords).toEqual(['select', 'insert']))
+
+ editor2.unmount()
+ })
+})
diff --git a/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.ts b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.ts
index 490c9b3a86a..8e903636956 100644
--- a/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.ts
+++ b/apps/studio/components/interfaces/SQLEditor/useAddDefinitions.ts
@@ -1,11 +1,13 @@
import { Monaco } from '@monaco-editor/react'
+import { useQueryClient } from '@tanstack/react-query'
import { LOCAL_STORAGE_KEYS } from 'common'
import type { IDisposable } from 'monaco-editor'
-import { useEffect, useRef } from 'react'
+import { useEffect } from 'react'
import getPgsqlCompletionProvider from '@/components/ui/CodeEditor/Providers/PgSQLCompletionProvider'
import getPgsqlSignatureHelpProvider from '@/components/ui/CodeEditor/Providers/PgSQLSignatureHelpProvider'
import { useDatabaseFunctionsQuery } from '@/data/database-functions/database-functions-query'
+import { databaseKeys } from '@/data/database/keys'
import { useKeywordsQuery } from '@/data/database/keywords-query'
import { useSchemasQuery } from '@/data/database/schemas-query'
import { useTableColumnsQuery } from '@/data/database/table-columns-query'
@@ -15,6 +17,41 @@ import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { formatSql } from '@/lib/formatSql'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
+/**
+ * Prevents double registration of Monaco providers (e.g registerCompletionItemProvider)
+ */
+const sharedRegistrations = new Map<string, { count: number; disposable?: IDisposable }>()
+
+/**
+ * Shared across every `useAddDefinitions` instance so the registered pgsql completion/signature
+ * providers always read the freshest data from *any* currently active editor, not just whichever
+ * instance's `register()` factory happened to run first. Without this, the provider stays bound
+ * to a single per-instance ref: if that instance unmounts while a sibling editor is still active,
+ * `acquireSharedRegistration`'s ref-count doesn't reach zero (so nothing gets disposed), but the
+ * provider is left reading a ref that will never be written to again.
+ */
+const sharedPgInfoRef: { current: any } = { current: null }
+
+export function acquireSharedRegistration(key: string, register: () => IDisposable) {
+ const existing = sharedRegistrations.get(key)
+ if (existing) {
+ existing.count += 1
+ } else {
+ sharedRegistrations.set(key, { count: 1, disposable: register() })
+ }
+
+ return () => {
+ const entry = sharedRegistrations.get(key)
+ if (!entry) return
+
+ entry.count -= 1
+ if (entry.count <= 0) {
+ entry.disposable?.dispose()
+ sharedRegistrations.delete(key)
+ }
+ }
+}
+
export const useAddDefinitions = (
id: string,
monaco: Monaco | null,
@@ -22,6 +59,7 @@ export const useAddDefinitions = (
) => {
const { data: project } = useSelectedProjectQuery()
const snapV2 = useSqlEditorV2StateSnapshot()
+ const queryClient = useQueryClient()
const [intellisenseEnabled] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,
@@ -57,8 +95,6 @@ export const useAddDefinitions = (
{ enabled: enabled && intellisenseEnabled }
)
- const pgInfoRef = useRef<any>(null)
-
const filteredSchemas = useSchemasFilteredForHighAvailability(schemas)
const isPgInfoReady =
@@ -69,20 +105,47 @@ export const useAddDefinitions = (
isKeywordsSuccess &&
isFunctionsSuccess
- if (isPgInfoReady) {
- if (pgInfoRef.current === null) {
- pgInfoRef.current = {}
+ // Keeps `sharedPgInfoRef` current for the registered pgsql completion/signature-help
+ // providers. Runs in an effect — not render — so only committed tree state writes the
+ // shared, module-level ref; mutating it directly during render risked a discarded or
+ // interrupted render pass leaking a write that no committed render ever produced.
+ useEffect(() => {
+ if (isPgInfoReady) {
+ if (sharedPgInfoRef.current === null) {
+ sharedPgInfoRef.current = {}
+ }
+ sharedPgInfoRef.current.tableColumns = tableColumns
+ sharedPgInfoRef.current.schemas = filteredSchemas
+ sharedPgInfoRef.current.keywords = keywords
+ sharedPgInfoRef.current.functions = functions
+ } else if (!intellisenseEnabled) {
+ // Release this instance's hold on the (potentially huge, for large databases)
+ // tableColumns/functions arrays so they're actually eligible for GC — see the
+ // cache-eviction effect below for why `enabled: false` alone isn't enough.
+ sharedPgInfoRef.current = null
}
- pgInfoRef.current.tableColumns = tableColumns
- pgInfoRef.current.schemas = filteredSchemas
- pgInfoRef.current.keywords = keywords
- pgInfoRef.current.functions = functions
- }
+ }, [isPgInfoReady, intellisenseEnabled, tableColumns, filteredSchemas, keywords, functions])
+
+ // Actively evict the cached tableColumns/functions data when intellisense is turned off
+ useEffect(() => {
+ if (intellisenseEnabled) return
+
+ queryClient.removeQueries({
+ queryKey: databaseKeys.tableColumns(project?.ref, undefined, undefined),
+ exact: true,
+ })
+ queryClient.removeQueries({
+ queryKey: databaseKeys.databaseFunctions(project?.ref),
+ exact: true,
+ })
+ }, [intellisenseEnabled, project?.ref, queryClient])
// Enable pgsql format
useEffect(() => {
- if (monaco) {
- const formatProvider = monaco.languages.registerDocumentFormattingEditProvider('pgsql', {
+ if (!monaco || !enabled) return
+
+ return acquireSharedRegistration('pgsql-format', () =>
+ monaco.languages.registerDocumentFormattingEditProvider('pgsql', {
async provideDocumentFormattingEdits(model) {
const value = model.getValue()
const formatted = formatSql(value)
@@ -90,31 +153,29 @@ export const useAddDefinitions = (
return [{ range: model.getFullModelRange(), text: formatted }]
},
})
- return () => formatProvider.dispose()
- }
+ )
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [monaco])
+ }, [monaco, enabled])
// Register auto completion item provider for pgsql
useEffect(() => {
- let completeProvider: IDisposable | null = null
- let signatureHelpProvider: IDisposable | null = null
+ if (!isPgInfoReady || !monaco) return
- if (isPgInfoReady) {
- if (monaco && isPgInfoReady) {
- completeProvider = monaco.languages.registerCompletionItemProvider(
- 'pgsql',
- getPgsqlCompletionProvider(monaco, pgInfoRef)
- )
- signatureHelpProvider = monaco.languages.registerSignatureHelpProvider(
- 'pgsql',
- getPgsqlSignatureHelpProvider(monaco, pgInfoRef)
- )
+ return acquireSharedRegistration('pgsql-completion', () => {
+ const completeProvider = monaco.languages.registerCompletionItemProvider(
+ 'pgsql',
+ getPgsqlCompletionProvider(monaco, sharedPgInfoRef)
+ )
+ const signatureHelpProvider = monaco.languages.registerSignatureHelpProvider(
+ 'pgsql',
+ getPgsqlSignatureHelpProvider(monaco, sharedPgInfoRef)
+ )
+ return {
+ dispose: () => {
+ completeProvider.dispose()
+ signatureHelpProvider.dispose()
+ },
}
- }
- return () => {
- completeProvider?.dispose()
- signatureHelpProvider?.dispose()
- }
+ })
}, [isPgInfoReady, monaco])
}