Skip to content

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

Midway refactoring SQL editor to deprecate use of mobx store, e2e functionality is present

Joshen Limb1a8dc07658b
diff --git a/studio/components/interfaces/App/CommandMenuWrapper.tsx b/studio/components/interfaces/App/CommandMenuWrapper.tsx
index e4038a72b49..e6e82b2b3c1 100644
--- a/studio/components/interfaces/App/CommandMenuWrapper.tsx
+++ b/studio/components/interfaces/App/CommandMenuWrapper.tsx
@@ -7,7 +7,7 @@ import { useParams } from 'common/hooks'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useProfileQuery } from 'data/profile/profile-query'
import { uuidv4 } from 'lib/helpers'
-import { createSqlSnippetSkeleton } from 'components/to-be-cleaned/SqlEditor/SqlEditor.utils'
+import { createSqlSnippetSkeleton } from '../SQLEditor/SQLEditor.utils'
import { useProjectApiQuery } from 'data/config/project-api-query'
const CommandMenuWrapper = ({ children }: PropsWithChildren<{}>) => {
diff --git a/studio/components/interfaces/SQLEditor/MonacoEditor.tsx b/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
new file mode 100644
index 00000000000..f102bfe0ffa
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
@@ -0,0 +1,103 @@
+import Editor, { Monaco, OnMount } from '@monaco-editor/react'
+import { timeout } from 'lib/helpers'
+import { useEffect, useRef } from 'react'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+
+export type MonacoEditorProps = {
+ id: string
+ isExecuting: boolean
+ executeQuery: (overrideSql?: string) => void
+}
+
+const MonacoEditor = ({ id, isExecuting, executeQuery }: MonacoEditorProps) => {
+ const snap = useSqlEditorStateSnapshot({ sync: true })
+ const snippet = snap.snippets[id]
+
+ const editorRef = useRef<any>(null)
+ const monacoRef = useRef<Monaco | null>(null)
+ const executeQueryRef = useRef(executeQuery)
+ executeQueryRef.current = executeQuery
+
+ useEffect(() => {
+ if (!editorRef.current || !monacoRef.current) return
+
+ const model = editorRef.current.getModel()
+ monacoRef.current.editor.setModelMarkers(model, 'owner', [])
+ }, [])
+
+ useEffect(() => {
+ if (editorRef.current) {
+ // add margin above first line
+ editorRef.current?.changeViewZones((accessor: any) => {
+ accessor.addZone({
+ afterLineNumber: 0,
+ heightInPx: 4,
+ domNode: document.createElement('div'),
+ })
+ })
+ }
+ }, [])
+
+ const handleEditorOnMount: OnMount = async (editor, monaco) => {
+ editorRef.current = editor
+ monacoRef.current = monaco
+
+ editor.addAction({
+ id: 'supabase',
+ label: 'Run Query',
+ keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.Enter],
+ contextMenuGroupId: 'operation',
+ contextMenuOrder: 0,
+ run: () => {
+ // [Joshen TODO] If executing, prevent executing more
+ if (isExecuting) return
+
+ const selectedValue = (editorRef?.current)
+ .getModel()
+ .getValueInRange(editorRef?.current?.getSelection())
+
+ executeQueryRef.current?.(selectedValue || editorRef?.current?.getValue())
+ },
+ })
+
+ // add margin above first line
+ editor.changeViewZones((accessor: any) => {
+ accessor.addZone({
+ afterLineNumber: 0,
+ heightInPx: 4,
+ domNode: document.createElement('div'),
+ })
+ })
+
+ // when editor did mount, it will need a delay before focus() works properly
+ await timeout(500)
+ editor.focus()
+ }
+
+ function handleEditorChange(value: string | undefined) {
+ if (id && value) snap.setSql(id, value)
+ }
+
+ return (
+ <Editor
+ className="monaco-editor"
+ theme={'supabase'}
+ onMount={handleEditorOnMount}
+ onChange={handleEditorChange}
+ defaultLanguage="pgsql"
+ defaultValue={snippet?.snippet.content.sql}
+ path={id}
+ options={{
+ tabSize: 2,
+ fontSize: 13,
+ minimap: {
+ enabled: false,
+ },
+ wordWrap: 'on',
+ fixedOverflowWidgets: true,
+ }}
+ />
+ )
+}
+
+export default MonacoEditor
diff --git a/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx b/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
new file mode 100644
index 00000000000..239a026363e
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
@@ -0,0 +1,82 @@
+import { useParams } from 'common'
+import { useContentUpdateMutation } from 'data/content/content-update-mutation'
+import { useStore } from 'hooks'
+import { Button, Form, Input, Modal } from 'ui'
+
+export interface RenameQueryModalProps {
+ snippet: any
+ visible: boolean
+ onCancel: () => void
+ onComplete: () => void
+}
+
+const RenameQueryModal = ({ snippet, visible, onCancel, onComplete }: RenameQueryModalProps) => {
+ const { ui } = useStore()
+ const { ref } = useParams()
+ const { mutateAsync: updateContent } = useContentUpdateMutation()
+
+ const { id, name, description } = snippet
+
+ const validate = (values: any) => {
+ const errors: any = {}
+ if (!values.name) errors.name = 'Please enter a query name'
+ return errors
+ }
+
+ const onSubmit = async (values: any, { setSubmitting }: any) => {
+ if (!ref) return console.error('Project ref is required')
+ if (!id) return console.error('Snippet ID is required')
+
+ setSubmitting(true)
+ try {
+ await updateContent({ projectRef: ref, id, content: values })
+ if (onComplete) onComplete()
+ return Promise.resolve()
+ } catch (error: any) {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to rename query: ${error.message}`,
+ })
+ }
+ }
+
+ return (
+ <Modal visible={visible} onCancel={onCancel} hideFooter header="Rename" size="small">
+ <Form
+ onReset={onCancel}
+ validateOnBlur
+ initialValues={{
+ name: name ?? '',
+ description: description ?? '',
+ }}
+ validate={validate}
+ onSubmit={onSubmit}
+ >
+ {({ isSubmitting }: { isSubmitting: boolean }) => (
+ <div className="space-y-4 py-4">
+ <Modal.Content>
+ <Input label="Name" id="name" name="name" />
+ </Modal.Content>
+ <Modal.Content>
+ <Input label="Description" id="description" placeholder="Describe query" />
+ </Modal.Content>
+ <Modal.Separator />
+ <Modal.Content>
+ <div className="flex items-center justify-end gap-2">
+ <Button htmlType="reset" type="default" onClick={onCancel} disabled={isSubmitting}>
+ Cancel
+ </Button>
+ <Button htmlType="submit" loading={isSubmitting} disabled={isSubmitting}>
+ Rename query
+ </Button>
+ </div>
+ </Modal.Content>
+ </div>
+ )}
+ </Form>
+ </Modal>
+ )
+}
+
+export default RenameQueryModal
diff --git a/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts b/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts
index f1b8e5c4c85..5c98c1d5440 100644
--- a/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts
+++ b/studio/components/interfaces/SQLEditor/SQLEditor.constants.ts
@@ -1,3 +1,4 @@
+import { SqlSnippets, UserContent } from 'types'
import { SQLTemplate } from './SQLEditor.types'
export const SQL_TEMPLATES: SQLTemplate[] = [
@@ -1070,5 +1071,20 @@ select
'table hit rate' as name,
sum(heap_blks_hit) / nullif(sum(heap_blks_hit) + sum(heap_blks_read),0) as ratio
from pg_statio_user_tables;`,
- }
+ },
]
+
+export const SQL_SNIPPET_SCHEMA_VERSION = '1.0'
+
+export const NEW_SQL_SNIPPET_SKELETON: UserContent<SqlSnippets.Content> = {
+ name: 'New Query',
+ description: '',
+ type: 'sql',
+ visibility: 'user', // default to user scope
+ content: {
+ schema_version: SQL_SNIPPET_SCHEMA_VERSION,
+ content_id: '',
+ sql: 'this is a test',
+ favorite: false,
+ },
+}
diff --git a/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/studio/components/interfaces/SQLEditor/SQLEditor.tsx
new file mode 100644
index 00000000000..70ee7c5fbe7
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -0,0 +1,93 @@
+import { useParams } from 'common'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+// import { useWindowDimensions } from 'hooks'
+import { useCallback, useRef } from 'react'
+import Split from 'react-split'
+import { getSqlEditorStateSnapshot, useSqlEditorStateSnapshot } from 'state/sql-editor'
+import MonacoEditor from './MonacoEditor'
+import UtilityPanel from './UtilityPanel/UtilityPanel'
+import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
+
+export interface SQLEditorProps {}
+
+const SQLEditor = () => {
+ const { ref, id } = useParams()
+ const { project } = useProjectContext()
+ const snap = useSqlEditorStateSnapshot()
+
+ const { mutate: execute, isLoading: isExecuting } = useExecuteSqlMutation({
+ onSuccess(data) {
+ if (id) snap.addResult(id, data.result)
+ },
+ onError(error) {
+ if (id) snap.addResultError(id, error)
+ },
+ })
+
+ const idRef = useRef(id)
+ idRef.current = id
+
+ const minSize = 44
+ const snippet = id ? snap.snippets[id] : null
+ const snapOffset = 50
+ // const tabMenuHeight = 44
+ // const offset = 3
+
+ const isLoading = !(id && ref && snap.loaded[ref])
+
+ const onDragEnd = useCallback((sizes: number[]) => {
+ const id = idRef.current
+ if (id) snap.setSplitSizes(id, sizes)
+ }, [])
+
+ const executeQuery = useCallback(
+ (overrideSql?: string) => {
+ // use the latest state
+ const state = getSqlEditorStateSnapshot()
+ const snippet = id && state.snippets[id]
+
+ if (project && snippet && !isExecuting) {
+ execute?.({
+ projectRef: project.ref,
+ connectionString: project.connectionString,
+ sql: overrideSql ?? snippet.snippet.content.sql,
+ })
+ }
+ },
+ [isExecuting, project]
+ )
+
+ return (
+ <div className="flex h-full flex-col">
+ <Split
+ style={{ height: '100%' }}
+ direction="vertical"
+ gutterSize={2}
+ sizes={(snippet?.splitSizes as number[] | undefined) ?? [50, 50]}
+ minSize={minSize}
+ snapOffset={snapOffset}
+ expandToMin={true}
+ collapsed={snippet?.utilityPanelCollapsed ? 1 : undefined}
+ onDragEnd={onDragEnd}
+ >
+ <div className="dark:border-dark flex-grow overflow-y-auto border-b">
+ {isLoading ? (
+ <div className="flex h-full w-full items-center justify-center">Loading...</div>
+ ) : (
+ <MonacoEditor id={id!} isExecuting={isExecuting} executeQuery={executeQuery} />
+ )}
+ </div>
+
+ <div className="flex flex-col">
+ {isLoading ? (
+ <div className="flex h-full w-full items-center justify-center">Loading...</div>
+ ) : (
+ <UtilityPanel id={id!} isExecuting={isExecuting} executeQuery={executeQuery} />
+ )}
+ </div>
+ </Split>
+ </div>
+ )
+}
+
+export default SQLEditor
diff --git a/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts b/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
index 32379ae652f..1b5bdee8ee3 100644
--- a/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
+++ b/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
@@ -1,5 +1,7 @@
// @ts-ignore
import MarkdownTable from 'markdown-table'
+import { NEW_SQL_SNIPPET_SKELETON } from './SQLEditor.constants'
+import { SqlSnippets, UserContent } from 'types'
export const getResultsMarkdown = (results: any[]) => {
const columns = Object.keys(results[0])
@@ -11,3 +13,24 @@ export const getResultsMarkdown = (results: any[]) => {
const table = [columns].concat(rows)
return MarkdownTable(table)
}
+
+export const createSqlSnippetSkeleton = ({
+ name,
+ sql,
+ owner_id,
+}: {
+ name?: string
+ sql?: string
+ owner_id?: number
+} = {}): UserContent<SqlSnippets.Content> => {
+ return {
+ ...NEW_SQL_SNIPPET_SKELETON,
+ ...(name && { name }),
+ ...(owner_id && { owner_id }),
+ content: {
+ ...NEW_SQL_SNIPPET_SKELETON.content,
+ content_id: '',
+ sql: sql ?? '',
+ },
+ }
+}
diff --git a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLCard.tsx b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLCard.tsx
index 028c6f468ac..b02cab1ca40 100644
--- a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLCard.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLCard.tsx
@@ -1,38 +1,27 @@
-import { FC, useState } from 'react'
-import { IconChevronRight, IconLoader } from 'ui'
-import { SQLTemplate } from '../SQLEditor.types'
+import { useState } from 'react'
+import CardButton from 'components/ui/CardButton'
-interface Props {
- template: SQLTemplate
+export interface SQLCardProps {
+ title: string
+ description: string
+ sql: string
+ onClick: (sql: string, title: string) => void
}
-const SQLCard: FC<Props> = ({ template }) => {
- const { title, description } = template
+const SQLCard = ({ title, description, sql, onClick }: SQLCardProps) => {
const [loading, setLoading] = useState(false)
+ function handleOnClick() {
+ setLoading(true)
+ onClick(sql, title)
+ }
return (
- <div
- className="w-full cursor-pointer rounded border
- border-panel-border-light bg-panel-header-light transition-colors
- hover:border-panel-border-hover-light dark:border-panel-border-dark
- dark:bg-panel-header-dark dark:hover:border-panel-border-hover-dark"
- >
- <div className="flex items-center justify-between border-b px-6 py-3 dark:border-dark">
- <h5 className="m-0">{title}</h5>
- {loading ? (
- <div className="animate-spin">
- <IconLoader size={16} />
- </div>
- ) : (
- <p className="text-scale-1000">
- <IconChevronRight />
- </p>
- )}
- </div>
- <p className="capitalize-first px-6 py-4">
- <p className="text-scale-1000">{description}</p>
- </p>
- </div>
+ <CardButton
+ title={title}
+ loading={loading}
+ onClick={() => handleOnClick()}
+ footer={<span className="text-scale-1100 text-sm">{description}</span>}
+ />
)
}
diff --git a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
index d332d4e9159..3e52f968615 100644
--- a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
@@ -1,64 +1,123 @@
-import { FC } from 'react'
-import Link from 'next/link'
-import { observer } from 'mobx-react-lite'
import { partition } from 'lodash'
+import { observer } from 'mobx-react-lite'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useStore } from 'hooks'
+import Telemetry from 'lib/telemetry'
+import { checkPermissions, useStore } from 'hooks'
+import { useProfileQuery } from 'data/profile/profile-query'
+import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.constants'
import SQLCard from './SQLCard'
-import { SQL_TEMPLATES } from '../SQLEditor.constants'
+import { useContentCreateMutation } from 'data/content/content-create-mutation'
+import { createSqlSnippetSkeleton } from '../SQLEditor.utils'
+import { useParams } from 'common'
+import { useRouter } from 'next/router'
-interface Props {}
-
-const SQLTemplates: FC<Props> = ({}) => {
- const [templates, quickstarts] = partition(SQL_TEMPLATES, { type: 'template' })
+const SQLTemplates = observer(() => {
const { ui } = useStore()
- const projectRef = ui.selectedProject?.ref
+ const { ref } = useParams()
+ const router = useRouter()
+ const { data: profile } = useProfileQuery()
+ const [sql, quickStart] = partition(SQL_TEMPLATES, { type: 'template' })
+
+ const { mutateAsync: createContent } = useContentCreateMutation()
+ const canCreateSQLSnippet = checkPermissions(PermissionAction.CREATE, 'user_content', {
+ resource: { type: 'sql', owner_id: profile?.id },
+ subject: { id: profile?.id },
+ })
+
+ // [Joshen TODO] Removed optimistic query creation logic for now, need to figure out
+ // how to do that after using ids as part of the URL
+ const handleNewQuery = async (sql: string, name: string) => {
+ if (!ref) return console.error('Project ref is required')
+ if (!canCreateSQLSnippet) {
+ return ui.setNotification({
+ category: 'info',
+ message: 'Your queries will not be saved as you do not have sufficient permissions',
+ })
+ }
+
+ try {
+ const payload = createSqlSnippetSkeleton({ sql, name, owner_id: profile?.id })
+ const response = await createContent({ projectRef: ref, payload })
+ const snippetId = response.content[0].id
+ router.push(`/project/${ref}/sql/${snippetId}`)
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to create new query: ${error.message}`,
+ })
+ }
+ }
return (
- <div className="p-6 h-full overflow-y-auto space-y-8">
- <div className="flex flex-col">
+ <div className="block h-full space-y-8 overflow-y-auto p-6">
+ <div>
<div className="mb-4">
- <h4 className="text-lg mb-0">Scripts</h4>
- <p>
- Quick scripts to run on your database.
- <br />
+ <h1 className="text-scale-1200 mb-3 text-xl">Scripts</h1>
+ <p className="text-scale-1100 text-sm">Quick scripts to run on your database.</p>
+ <p className="text-scale-1100 text-sm">
Click on any script to fill the query box, modify the script, then click
- <code>Run</code>. More scripts coming soon!
+ <span className="text-code">Run</span>.
</p>
</div>
- <div className="grid grid-cols-3 gap-4">
- {templates.map((template) => (
- <Link key={template.id} href={`/project/${projectRef}/sql?templateId=${template.id}`}>
- <div className="flex flex-grow">
- <SQLCard template={template} />
- </div>
- </Link>
+ <div className="grid gap-4 sm:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
+ {sql.map((x) => (
+ <SQLCard
+ key={x.title}
+ title={x.title}
+ description={x.description}
+ sql={x.sql}
+ onClick={(sql, title) => {
+ handleNewQuery(sql, title)
+ Telemetry.sendEvent(
+ {
+ category: 'scripts',
+ action: 'script_clicked',
+ label: x.title,
+ },
+ ui.googleAnalyticsProps
+ )
+ }}
+ />
))}
</div>
</div>
- <div className="flex flex-col">
+ <div className="mb-8">
<div className="mb-4">
- <h4 className="text-lg mb-0">Quick start</h4>
- <p>
+ <h1 className="text-scale-1200 mb-3 text-xl">Quick start</h1>
+ <p className="text-scale-1100 text-sm">
While we're in beta, we want to offer a quick way to explore Supabase. While we build
importers, check out these simple starters.
- <br />
- Click on any script to fill the query box, modify the script, then click{' '}
- <code>Run</code>. More coming soon!
+ </p>
+ <p className="text-scale-1100 text-sm">
+ Click on any script to fill the query box, modify the script, then click
+ <span className="text-code">Run</span>.
</p>
</div>
- <div className="grid grid-cols-3 gap-4">
- {quickstarts.map((template) => (
- <Link key={template.id} href={`/project/${projectRef}/sql?templateId=${template.id}`}>
- <div className="flex flex-grow">
- <SQLCard template={template} />
- </div>
- </Link>
+ <div className="grid gap-4 sm:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
+ {quickStart.map((x) => (
+ <SQLCard
+ key={x.title}
+ title={x.title}
+ description={x.description}
+ sql={x.sql}
+ onClick={(sql, title) => {
+ handleNewQuery(sql, title)
+ Telemetry.sendEvent(
+ {
+ category: 'quickstart',
+ action: 'quickstart_clicked',
+ label: x.title,
+ },
+ ui.googleAnalyticsProps
+ )
+ }}
+ />
))}
</div>
</div>
</div>
)
-}
+})
-export default observer(SQLTemplates)
+export default SQLTemplates
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/FavoriteButton.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/FavoriteButton.tsx
new file mode 100644
index 00000000000..6cb1432b542
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/FavoriteButton.tsx
@@ -0,0 +1,98 @@
+import { Button, IconHeart } from '@supabase/ui'
+import { useQueryClient } from '@tanstack/react-query'
+import { contentKeys } from 'data/content/keys'
+import { Content, ContentData } from 'data/content/content-query'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+
+export type FavoriteButtonProps = { id: string }
+const FavoriteButton = ({ id }: FavoriteButtonProps) => {
+ const { project } = useProjectContext()
+ const snap = useSqlEditorStateSnapshot()
+ const isFavorite = snap.snippets[id].snippet.content.favorite
+ const client = useQueryClient()
+
+ async function addFavorite() {
+ snap.addFavorite(id)
+
+ client.setQueryData<ContentData>(
+ contentKeys.list(project?.ref),
+ (oldData: ContentData | undefined) => {
+ if (!oldData) {
+ return
+ }
+
+ return {
+ ...oldData,
+ content: oldData.content.map((content: Content) => {
+ if (content.type === 'sql' && content.id === id) {
+ return {
+ ...content,
+ content: {
+ ...content.content,
+ favorite: true,
+ },
+ }
+ }
+
+ return content
+ }),
+ }
+ }
+ )
+ }
+
+ async function removeFavorite() {
+ snap.removeFavorite(id)
+
+ client.setQueryData<ContentData>(
+ contentKeys.list(project?.ref),
+ (oldData: ContentData | undefined) => {
+ if (!oldData) {
+ return
+ }
+
+ return {
+ ...oldData,
+ content: oldData.content.map((content: Content) => {
+ if (content.type === 'sql' && content.id === id) {
+ return {
+ ...content,
+ content: {
+ ...content.content,
+ favorite: false,
+ },
+ }
+ }
+
+ return content
+ }),
+ }
+ }
+ )
+ }
+
+ return (
+ <>
+ {isFavorite ? (
+ <Button
+ type="text"
+ size="tiny"
+ shadow={false}
+ onClick={removeFavorite}
+ icon={<IconHeart size="tiny" fill="#48bb78" />}
+ />
+ ) : (
+ <Button
+ type="text"
+ size="tiny"
+ shadow={false}
+ onClick={addFavorite}
+ icon={<IconHeart size="tiny" fill="gray" />}
+ />
+ )}
+ </>
+ )
+}
+
+export default FavoriteButton
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx
new file mode 100644
index 00000000000..c0d3cb273fd
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx
@@ -0,0 +1,78 @@
+import DataGrid from '@supabase/react-data-grid'
+import { useKeyboardShortcuts } from 'hooks'
+import { copyToClipboard } from 'lib/helpers'
+import { useState } from 'react'
+
+const Results = ({ rows }: { rows: readonly any[] }) => {
+ const [cellPosition, setCellPosition] = useState<any>(undefined)
+
+ useKeyboardShortcuts(
+ {
+ 'Command+c': (event: any) => {
+ event.stopPropagation()
+ onCopyCell()
+ },
+ 'Control+c': (event: any) => {
+ event.stopPropagation()
+ onCopyCell()
+ },
+ },
+ ['INPUT', 'TEXTAREA'] as any
+ )
+
+ if (rows.length <= 0) {
+ return (
+ <div className="bg-table-header-light dark:bg-table-header-dark">
+ <p className="m-0 border-0 px-6 py-4 font-mono text-sm">Success. No rows returned</p>
+ </div>
+ )
+ }
+
+ const formatter = (column: any, row: any) => {
+ return <span className="font-mono text-xs">{JSON.stringify(row[column])}</span>
+ }
+ const columnRender = (name: string) => {
+ return <div className="flex h-full items-center justify-center font-mono">{name}</div>
+ }
+ const columns = Object.keys(rows[0]).map((key) => ({
+ key,
+ name: key,
+ formatter: ({ row }: any) => formatter(key, row),
+ headerRenderer: () => columnRender(key),
+ resizable: true,
+ width: 120,
+ }))
+
+ function onSelectedCellChange(position: any) {
+ setCellPosition(position)
+ }
+
+ function onCopyCell() {
+ if (columns && cellPosition) {
+ const { idx, rowIdx } = cellPosition
+ const colKey = columns[idx].key
+ const cellValue = rows[rowIdx]?.[colKey] ?? ''
+ const value = formatClipboardValue(cellValue)
+ copyToClipboard(value)
+ }
+ }
+
+ return (
+ <DataGrid
+ columns={columns}
+ rows={rows}
+ style={{ height: '100%' }}
+ onSelectedCellChange={onSelectedCellChange}
+ />
+ )
+}
+
+export default Results
+
+function formatClipboardValue(value: any) {
+ if (value === null) return ''
+ if (typeof value == 'object' || Array.isArray(value)) {
+ return JSON.stringify(value)
+ }
+ return value
+}
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/ResultsDropdown.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/ResultsDropdown.tsx
new file mode 100644
index 00000000000..b59ec3b6c22
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/ResultsDropdown.tsx
@@ -0,0 +1,88 @@
+import { Button, Dropdown, IconChevronDown } from '@supabase/ui'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useStore } from 'hooks'
+import { copyToClipboard } from 'lib/helpers'
+import Telemetry from 'lib/telemetry'
+import { compact } from 'lodash'
+import { useMemo, useRef } from 'react'
+import { CSVLink } from 'react-csv'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+// import MarkdownTable from 'markdown-table'
+
+export type ResultsDropdownProps = {
+ id: string
+}
+
+const ResultsDropdown = ({ id }: ResultsDropdownProps) => {
+ const { project } = useProjectContext()
+ const snap = useSqlEditorStateSnapshot()
+ const result = snap.results?.[id]?.[0] ?? undefined
+ const { ui } = useStore()
+ const csvRef = useRef<CSVLink & HTMLAnchorElement & { link: HTMLAnchorElement }>(null)
+
+ const csvData = useMemo(
+ () => (result?.rows ? compact(Array.from(result.rows || [])) : ''),
+ [result?.rows]
+ )
+
+ function onDownloadCSV() {
+ csvRef.current?.link.click()
+ Telemetry.sendEvent(
+ { category: 'sql_editor', action: 'sql_download_csv', label: '' },
+ ui.googleAnalyticsProps
+ )
+ }
+
+ function onCopyAsMarkdown() {
+ if (navigator) {
+ if (!result || !result.rows) return 'results is empty'
+ if (result.rows.constructor !== Array && !!result.error) return result.error
+ if (result.rows.length == 0) return 'results is empty'
+
+ const columns = Object.keys(result.rows[0])
+ const rows = result.rows.map((x) => {
+ let temp: any[] = []
+ columns.forEach((col) => temp.push(x[col]))
+ return temp
+ })
+ const table = [columns].concat(rows)
+ console.log('Copy', table)
+
+ // [Joshen TODO] Fix below
+ // const markdownData = MarkdownTable(table)
+
+ // copyToClipboard(markdownData, () => {
+ // ui.setNotification({ category: 'success', message: 'Copied results to clipboard' })
+ // Telemetry.sendEvent(
+ // { category: 'sql_editor', action: 'sql_copy_as_markdown', label: '' },
+ // ui.googleAnalyticsProps
+ // )
+ // })
+ }
+ }
+
+ return (
+ <Dropdown
+ side="bottom"
+ align="start"
+ overlay={
+ <>
+ <Dropdown.Item onClick={onDownloadCSV}>Download CSV</Dropdown.Item>
+ <Dropdown.Item onClick={onCopyAsMarkdown}>Copy as markdown</Dropdown.Item>
+ </>
+ }
+ >
+ <Button as="span" type="text" iconRight={<IconChevronDown />}>
+ Results
+ </Button>
+ <CSVLink
+ ref={csvRef}
+ className="hidden"
+ data={csvData}
+ filename={`supabase_${project?.ref}_${snap.snippets[id]?.snippet.name}`}
+ />
+ </Dropdown>
+ )
+}
+
+export default ResultsDropdown
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/SavingIndicator.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/SavingIndicator.tsx
new file mode 100644
index 00000000000..28dcdd37f7c
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/SavingIndicator.tsx
@@ -0,0 +1,94 @@
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { Button, IconAlertCircle, IconCheck, IconLoader, IconRefreshCcw } from '@supabase/ui'
+import { usePrevious } from 'hooks'
+import { useEffect, useState } from 'react'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+
+export type SavingIndicatorProps = { id: string }
+
+const SavingIndicator = ({ id }: SavingIndicatorProps) => {
+ const snap = useSqlEditorStateSnapshot()
+ const savingState = snap.savingStates[id]
+
+ const previousState = usePrevious(savingState)
+ const [showSavedText, setShowSavedText] = useState(false)
+
+ useEffect(() => {
+ let cancel = false
+
+ if (previousState === 'UPDATING' && savingState === 'IDLE') {
+ setShowSavedText(true)
+ setTimeout(() => {
+ if (!cancel) setShowSavedText(false)
+ }, 3000)
+ }
+
+ return () => {
+ cancel = true
+ }
+ }, [savingState])
+
+ const retry = () => {
+ snap.addNeedsSaving(id)
+ }
+
+ return (
+ <div className="mx-2 flex items-center gap-2">
+ {savingState === 'UPDATING_FAILED' && (
+ <Button
+ type="text"
+ size="tiny"
+ shadow={false}
+ icon={<IconRefreshCcw className="text-gray-1100" size="tiny" strokeWidth={2} />}
+ onClick={retry}
+ >
+ Retry
+ </Button>
+ )}
+ {savingState === 'UPDATING' && (
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger>
+ <IconLoader className="animate-spin" size={14} strokeWidth={2} />
+ </Tooltip.Trigger>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'bg-scale-100 rounded py-1 px-2 leading-none shadow',
+ 'border-scale-200 border',
+ ].join(' ')}
+ >
+ <span className="text-scale-1200 text-xs">Saving changes...</span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Root>
+ )}
+ {savingState === 'UPDATING_FAILED' && (
+ <IconAlertCircle className="text-red-900" size={14} strokeWidth={2} />
+ )}
+ {showSavedText && (
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger>
+ <IconCheck className="text-brand-800" size={14} strokeWidth={3} />
+ </Tooltip.Trigger>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'bg-scale-100 rounded py-1 px-2 leading-none shadow',
+ 'border-scale-200 border ',
+ ].join(' ')}
+ >
+ <span className="text-scale-1200 text-xs">All changes saved</span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Root>
+ )}
+ <span className="text-scale-1000 text-sm">
+ {savingState === 'UPDATING_FAILED' && 'Failed to save'}
+ </span>
+ </div>
+ )
+}
+
+export default SavingIndicator
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
new file mode 100644
index 00000000000..a8a2fb16c3a
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
@@ -0,0 +1,74 @@
+import { Button, IconChevronDown, IconChevronUp } from '@supabase/ui'
+import { IS_PLATFORM } from 'lib/constants'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+import FavoriteButton from './FavoriteButton'
+import SavingIndicator from './SavingIndicator'
+
+export type UtilityActionsProps = {
+ id: string
+ isExecuting?: boolean
+ executeQuery?: (overrideSql?: string) => void
+}
+
+const UtilityActions = ({ id, isExecuting = false, executeQuery }: UtilityActionsProps) => {
+ return (
+ <>
+ <SavingIndicator id={id} />
+ {IS_PLATFORM && <FavoriteButton id={id} />}
+ <SizeToggleButton id={id} />
+ <Button
+ onClick={() => executeQuery?.()}
+ disabled={isExecuting}
+ loading={isExecuting}
+ type="text"
+ size="tiny"
+ shadow={false}
+ className="mx-2"
+ >
+ RUN
+ </Button>
+ </>
+ )
+}
+const SizeToggleButton = ({ id }: { id: string }) => {
+ const snap = useSqlEditorStateSnapshot()
+ const snippet = snap.snippets[id]
+
+ function maximizeEditor() {
+ snap.collapseUtilityPanel(id)
+ }
+
+ function restorePanelSize() {
+ snap.restoreUtilityPanel(id)
+ }
+
+ return snippet.utilityPanelCollapsed ? (
+ <Button
+ type="text"
+ size="tiny"
+ shadow={false}
+ onClick={restorePanelSize}
+ icon={<IconChevronUp className="text-gray-1100" size="tiny" strokeWidth={2} />}
+ // @ts-ignore
+ tooltip={{
+ title: 'Restore panel size',
+ position: 'top',
+ }}
+ />
+ ) : (
+ <Button
+ type="text"
+ size="tiny"
+ shadow={false}
+ onClick={maximizeEditor}
+ icon={<IconChevronDown className="text-gray-1100" size="tiny" strokeWidth={2} />}
+ // @ts-ignore
+ tooltip={{
+ title: 'Maximize editor',
+ position: 'top',
+ }}
+ />
+ )
+}
+
+export default UtilityActions
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
new file mode 100644
index 00000000000..c7f1f8c0e5b
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
@@ -0,0 +1,29 @@
+import ResultsDropdown from './ResultsDropdown'
+import UtilityActions from './UtilityActions'
+import UtilityTabResults from './UtilityTabResults'
+
+export type UtilityPanelProps = {
+ id: string
+ isExecuting?: boolean
+ executeQuery?: (overrideSql?: string) => void
+}
+
+const UtilityPanel = ({ id, isExecuting, executeQuery }: UtilityPanelProps) => {
+ return (
+ <>
+ <div className="flex justify-between overflow-visible px-6 py-2">
+ <ResultsDropdown id={id} />
+
+ <div className="inline-flex items-center justify-end">
+ <UtilityActions id={id} isExecuting={isExecuting} executeQuery={executeQuery} />
+ </div>
+ </div>
+
+ <div className="flex-1 p-0 pt-0 pb-0">
+ <UtilityTabResults id={id} isExecuting={isExecuting} />
+ </div>
+ </>
+ )
+}
+
+export default UtilityPanel
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityResults.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityResults.tsx
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
new file mode 100644
index 00000000000..0a4b24aaa22
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
@@ -0,0 +1,49 @@
+import { Typography } from '@supabase/ui'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+import Results from './Results'
+
+export type UtilityTabResultsProps = {
+ id: string
+ isExecuting?: boolean
+}
+
+const UtilityTabResults = ({ id, isExecuting }: UtilityTabResultsProps) => {
+ const snap = useSqlEditorStateSnapshot()
+ const utilityPanelCollapsed = snap.snippets[id].utilityPanelCollapsed
+ const result = snap.results[id][0]
+
+ if (utilityPanelCollapsed) return null
+ if (isExecuting) {
+ return (
+ <div className="bg-table-header-light dark:bg-table-header-dark">
+ <p className="m-0 border-0 px-6 py-4 font-mono text-sm">Running...</p>
+ </div>
+ )
+ } else if (result?.error) {
+ return (
+ <div className="bg-table-header-light dark:bg-table-header-dark">
+ <Typography.Text>
+ <p className="m-0 border-0 px-6 py-4 font-mono">{result.error.message ?? result.error}</p>
+ </Typography.Text>
+ </div>
+ )
+ } else if (!result) {
+ return (
+ <div className="bg-table-header-light dark:bg-table-header-dark">
+ <Typography.Text type="secondary">
+ <p className="m-0 border-0 px-6 py-4 ">
+ Click <Typography.Text code>RUN</Typography.Text> to execute your query.
+ </p>
+ </Typography.Text>
+ </div>
+ )
+ }
+
+ return (
+ <div className="h-full">
+ <Results rows={result.rows} />
+ </div>
+ )
+}
+
+export default UtilityTabResults
diff --git a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
index 71a37032b0f..7b50ddfb020 100644
--- a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
+++ b/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
@@ -143,3 +143,40 @@ const ContentWrapper: FC<ContentWrapperProps> = observer(({ isLoading, children
</>
)
})
+
+export const ProjectLayoutNonBlocking = ({
+ title,
+ product = '',
+ productMenu,
+ children,
+ hideHeader = false,
+ hideIconBar = false,
+}: PropsWithChildren<Props>) => {
+ const { ref: projectRef } = useParams()
+ const ongoingIncident = useFlag('ongoingIncident')
+
+ return (
+ <ProjectContextProvider projectRef={projectRef}>
+ <Head>
+ <title>{title ? `${title} | Supabase` : 'Supabase'}</title>
+ <meta name="description" content="Supabase Studio" />
+ <link rel="icon" href="/favicon.ico" />
+ </Head>
+ <div className="flex h-full">
+ {/* Left-most navigation side bar to access products */}
+ {!hideIconBar && <NavigationBar />}
+
+ {/* Product menu bar */}
+ {productMenu && <ProductMenuBar title={product}>{productMenu}</ProductMenuBar>}
+
+ <main
+ className="flex w-full flex-1 flex-col overflow-x-hidden"
+ style={{ height: ongoingIncident ? 'calc(100vh - 44px)' : '100vh' }}
+ >
+ {!hideHeader && <LayoutHeader />}
+ {children}
+ </main>
+ </div>
+ </ProjectContextProvider>
+ )
+}
diff --git a/studio/components/layouts/SQLEditorLayout/QueryItem.tsx b/studio/components/layouts/SQLEditorLayout/QueryItem.tsx
new file mode 100644
index 00000000000..ef34223da2c
--- /dev/null
+++ b/studio/components/layouts/SQLEditorLayout/QueryItem.tsx
@@ -0,0 +1,123 @@
+import { useState } from 'react'
+import { useParams } from 'common'
+import QueryTab from 'localStores/sqlEditor/QueryTab'
+import ProductMenuItem from 'components/ui/ProductMenu/ProductMenuItem'
+import ConfirmationModal from 'components/ui/ConfirmationModal'
+import { useContentDeleteMutation } from 'data/content/content-delete-mutation'
+import { useStore } from 'hooks'
+import { IS_PLATFORM } from 'lib/constants'
+import { observer } from 'mobx-react-lite'
+import { Dropdown, IconEdit2, IconTrash, Button, IconChevronDown, Modal } from 'ui'
+import RenameQueryModal from 'components/interfaces/SQLEditor/RenameQueryModal'
+
+export interface QueryItemProps {
+ tabInfo: QueryTab
+ canCreateSQLSnippet: boolean
+}
+
+const QueryItem = ({ tabInfo, canCreateSQLSnippet }: QueryItemProps) => {
+ const { ref, id: activeId } = useParams()
+ const { id, name } = tabInfo || {}
+ const active = id === activeId
+
+ return (
+ <ProductMenuItem
+ key={id}
+ isActive={active}
+ name={name}
+ action={active && canCreateSQLSnippet && <QueryItemActions tabInfo={tabInfo} />}
+ textClassName="w-44"
+ url={`/project/${ref}/sql/${id}`}
+ />
+ )
+}
+
+export default QueryItem
+
+const QueryItemActions = observer(({ tabInfo }: { tabInfo: QueryTab }) => {
+ const { ui } = useStore()
+ const { ref } = useParams()
+ const { mutateAsync: deleteContent } = useContentDeleteMutation()
+
+ const { id, name } = tabInfo || {}
+ const [renameModalOpen, setRenameModalOpen] = useState(false)
+ const [deleteModalOpen, setDeleteModalOpen] = useState(false)
+
+ const onCloseRenameModal = () => {
+ setRenameModalOpen(false)
+ }
+
+ const onClickRename = (e: any) => {
+ e.stopPropagation()
+ setRenameModalOpen(true)
+ }
+
+ const onClickDelete = (e: any) => {
+ e.stopPropagation()
+ setDeleteModalOpen(true)
+ }
+
+ const onConfirmDelete = async () => {
+ if (!ref) return console.error('Project ref is required')
+
+ try {
+ await deleteContent({ projectRef: ref, id })
+ // [Joshen TODO] Needs to load another tab through router push
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to create new query: ${error.message}`,
+ })
+ }
+ }
+
+ return (
+ <div>
+ {IS_PLATFORM ? (
+ <Dropdown
+ side="bottom"
+ align="end"
+ overlay={
+ <>
+ <Dropdown.Item onClick={onClickRename} icon={<IconEdit2 size="tiny" />}>
+ Rename query
+ </Dropdown.Item>
+ <Dropdown.Separator />
+ <Dropdown.Item onClick={onClickDelete} icon={<IconTrash size="tiny" />}>
+ Remove query
+ </Dropdown.Item>
+ </>
+ }
+ >
+ <Button
+ as="span"
+ type="text"
+ icon={<IconChevronDown size={12} />}
+ style={{ padding: '3px' }}
+ />
+ </Dropdown>
+ ) : (
+ <Button as="span" type="text" style={{ padding: '3px' }} />
+ )}
+
+ <RenameQueryModal
+ snippet={tabInfo}
+ visible={renameModalOpen}
+ onCancel={onCloseRenameModal}
+ onComplete={onCloseRenameModal}
+ />
+
+ <ConfirmationModal
+ header="Confirm to remove"
+ buttonLabel="Confirm"
+ visible={deleteModalOpen}
+ onSelectConfirm={onConfirmDelete}
+ onSelectCancel={() => setDeleteModalOpen(false)}
+ >
+ <Modal.Content>
+ <p className="py-4 text-sm text-scale-1100">{`Are you sure you want to remove '${name}' ?`}</p>
+ </Modal.Content>
+ </ConfirmationModal>
+ </div>
+ )
+})
diff --git a/studio/components/layouts/SQLEditorLayout/SQLEditorLayout.tsx b/studio/components/layouts/SQLEditorLayout/SQLEditorLayout.tsx
index bee4b202877..2900812c16f 100644
--- a/studio/components/layouts/SQLEditorLayout/SQLEditorLayout.tsx
+++ b/studio/components/layouts/SQLEditorLayout/SQLEditorLayout.tsx
@@ -1,11 +1,6 @@
-import { ReactNode, useEffect } from 'react'
-import { observer } from 'mobx-react-lite'
-
-import { useStore, withAuth } from 'hooks'
-import { useProfileQuery } from 'data/profile/profile-query'
-import Error from 'components/ui/Error'
-import { useSqlEditorStore, SqlEditorContext } from 'localStores/sqlEditor/SqlEditorStore'
-import ProjectLayout from '../ProjectLayout/ProjectLayout'
+import { ReactNode, useMemo } from 'react'
+import { withAuth } from 'hooks'
+import { ProjectLayoutNonBlocking } from '../ProjectLayout/ProjectLayout'
import SQLEditorMenu from './SQLEditorMenu'
export interface SQLEditorLayoutProps {
@@ -14,36 +9,13 @@ export interface SQLEditorLayoutProps {
}
const SQLEditorLayout = ({ title, children }: SQLEditorLayoutProps) => {
- const { ui, content, meta } = useStore()
- const { data: profile } = useProfileQuery()
-
- const sqlEditorStore = useSqlEditorStore(ui.selectedProject?.ref, meta)
-
- useEffect(() => {
- if (sqlEditorStore) {
- // this calls content.load() for us, as well as loading tabs
- sqlEditorStore.loadRemotePersistentData(content, profile?.id)
- }
- }, [sqlEditorStore])
+ const productMenu = useMemo(() => <SQLEditorMenu key="sql-editor-menu" />, [])
return (
- <SqlEditorContext.Provider value={sqlEditorStore}>
- {content.error ? (
- <ProjectLayout>
- <Error error={content.error} />
- </ProjectLayout>
- ) : (
- <ProjectLayout
- isLoading={content.isLoading || sqlEditorStore === null}
- title={title || 'SQL'}
- product="SQL Editor"
- productMenu={<SQLEditorMenu />}
- >
- {children}
- </ProjectLayout>
- )}
- </SqlEditorContext.Provider>
+ <ProjectLayoutNonBlocking title={title || 'SQL'} product="SQL Editor" productMenu={productMenu}>
+ {children}
+ </ProjectLayoutNonBlocking>
)
}
-export default withAuth(observer(SQLEditorLayout))
+export default withAuth(SQLEditorLayout)
diff --git a/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx b/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
index 699839ab3df..b438b64be45 100644
--- a/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
+++ b/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
@@ -1,165 +1,82 @@
-import { useState } from 'react'
+import { partition } from 'lodash'
+import { useState, useMemo } from 'react'
import { observer } from 'mobx-react-lite'
-import {
- Button,
- Dropdown,
- Menu,
- Input,
- IconSearch,
- IconPlus,
- IconX,
- IconLoader,
- IconTrash,
- IconChevronDown,
- Modal,
- IconEdit2,
-} from 'ui'
+import { Button, Menu, Input, IconSearch, IconPlus, IconX } from 'ui'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useOptimisticSqlSnippetCreate, useStore, checkPermissions } from 'hooks'
+import { checkPermissions, useStore } from 'hooks'
import { IS_PLATFORM } from 'lib/constants'
-import QueryTab from 'localStores/sqlEditor/QueryTab'
-import { useSqlStore, TAB_TYPES } from 'localStores/sqlEditor/SqlEditorStore'
import { useProfileQuery } from 'data/profile/profile-query'
-import RenameQuery from 'components/to-be-cleaned/SqlEditor/RenameQuery'
-import ConfirmationModal from 'components/ui/ConfirmationModal'
import ProductMenuItem from 'components/ui/ProductMenu/ProductMenuItem'
-
-const OpenQueryItem = observer(
- ({ tabInfo, canCreateSQLSnippet }: { tabInfo: QueryTab; canCreateSQLSnippet: boolean }) => {
- const sqlEditorStore: any = useSqlStore()
- const { id, name } = tabInfo || {}
- const active = sqlEditorStore.activeTab.id === id
-
- return (
- <ProductMenuItem
- key={id}
- isActive={active}
- name={name}
- action={active && canCreateSQLSnippet && <DropdownMenu tabInfo={tabInfo} />}
- onClick={() => sqlEditorStore.selectTab(id)}
- textClassName="w-44"
- />
- )
- }
-)
-
-const DropdownMenu = observer(({ tabInfo }: { tabInfo: QueryTab }) => {
- const { data: profile } = useProfileQuery()
- const { content: contentStore } = useStore()
-
- const sqlEditorStore: any = useSqlStore()
-
- const [tabId, setTabId] = useState('')
- const [renameModalOpen, setRenameModalOpen] = useState(false)
- const [deleteModalOpen, setDeleteModalOpen] = useState(false)
-
- const { id, name } = tabInfo || {}
-
- function onCloseRenameModal() {
- setRenameModalOpen(false)
- }
-
- function renameQuery(e: any) {
- setTabId(id)
- setRenameModalOpen(true)
- }
-
- function renderMenu() {
- return (
- <>
- <Dropdown.Item onClick={renameQuery} icon={<IconEdit2 size="tiny" />}>
- Rename query
- </Dropdown.Item>
- <Dropdown.Separator />
- <Dropdown.Item onClick={() => setDeleteModalOpen(true)} icon={<IconTrash size="tiny" />}>
- Remove query
- </Dropdown.Item>
- </>
- )
- }
-
- return (
- <div>
- {IS_PLATFORM ? (
- <Dropdown side="bottom" align="end" overlay={renderMenu()}>
- <Button
- as="span"
- type="text"
- icon={<IconChevronDown size={12} />}
- style={{ padding: '3px' }}
- />
- </Dropdown>
- ) : (
- <Button as="span" type="text" style={{ padding: '3px' }} />
- )}
-
- <RenameQuery
- // @ts-ignore -- @mildtomato not sure what is wrong here
- visible={renameModalOpen}
- onCancel={onCloseRenameModal}
- tabId={tabId}
- onComplete={onCloseRenameModal}
- />
-
- <ConfirmationModal
- header="Confirm to remove"
- buttonLabel="Confirm"
- visible={deleteModalOpen}
- onSelectConfirm={async () => {
- sqlEditorStore.closeTab(id)
-
- await contentStore.del(id)
-
- sqlEditorStore.loadTabs(
- sqlEditorStore.tabsFromContentStore(contentStore, profile?.id),
- false
- )
- }}
- onSelectCancel={() => setDeleteModalOpen(false)}
- >
- <Modal.Content>
- <p className="py-4 text-sm text-scale-1100">{`Are you sure you want to remove '${name}' ?`}</p>
- </Modal.Content>
- </ConfirmationModal>
- </div>
- )
-})
+import { useParams } from 'common'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+import { useSqlSnippetsQuery } from 'data/content/sql-snippets-query'
+import ShimmeringLoader from 'components/ui/ShimmeringLoader'
+import QueryItem from './QueryItem'
+import { createSqlSnippetSkeleton } from 'components/interfaces/SQLEditor/SQLEditor.utils'
+import { useContentCreateMutation } from 'data/content/content-create-mutation'
+import { useRouter } from 'next/router'
const SideBarContent = observer(() => {
+ const { ui } = useStore()
+ const { ref, id } = useParams()
+ const router = useRouter()
const { data: profile } = useProfileQuery()
- const sqlEditorStore: any = useSqlStore()
const [filterString, setFilterString] = useState('')
- const canCreateSQLSnippet = checkPermissions(PermissionAction.CREATE, 'user_content', {
- resource: { type: 'sql', owner_id: profile?.id },
- subject: { id: profile?.id },
- })
-
- const handleNewQuery = useOptimisticSqlSnippetCreate(canCreateSQLSnippet)
-
- const getStartedTabs = (sqlEditorStore?.tabs ?? []).filter((tab: any) => {
- return tab.type === TAB_TYPES.WELCOME
+ const snap = useSqlEditorStateSnapshot()
+ const { data, isLoading, isSuccess } = useSqlSnippetsQuery(ref, {
+ onSuccess(data) {
+ if (ref) snap.setInitialSnippets(data.snippets, ref)
+ },
})
+ const { mutateAsync: createContent } = useContentCreateMutation()
- const favorites = (sqlEditorStore?.tabs ?? []).filter((tab: any) => {
- return tab.type !== TAB_TYPES.WELCOME && tab.favorite
- })
-
- const queries = (sqlEditorStore?.tabs ?? []).filter((tab: any) => {
- return tab.type !== TAB_TYPES.WELCOME && !tab.favorite
- })
+ const [favorites, queries] = useMemo(
+ () =>
+ data?.snippets ? partition(data.snippets, (snippet) => snippet.content.favorite) : [[], []],
+ [data?.snippets]
+ )
const favouriteTabs =
filterString.length === 0
? favorites
- : favorites.filter((tab: any) => tab.name.includes(filterString))
+ : favorites.filter((tab) => tab.name.toLowerCase().includes(filterString.toLowerCase()))
const queryTabs =
filterString.length === 0
? queries
- : queries.filter((tab: any) => tab.name.includes(filterString))
+ : queries.filter((tab) => tab.name.toLowerCase().includes(filterString.toLowerCase()))
+
+ const canCreateSQLSnippet = checkPermissions(PermissionAction.CREATE, 'user_content', {
+ resource: { type: 'sql', owner_id: profile?.id },
+ subject: { id: profile?.id },
+ })
+
+ // [Joshen TODO] Removed optimistic query creation logic for now, need to figure out
+ // how to do that after using ids as part of the URL
+ const handleNewQuery = async () => {
+ if (!ref) return console.error('Project ref is required')
+ if (!canCreateSQLSnippet) {
+ return ui.setNotification({
+ category: 'info',
+ message: 'Your queries will not be saved as you do not have sufficient permissions',
+ })
+ }
+
+ try {
+ const payload = createSqlSnippetSkeleton({ name: 'Untitled query', owner_id: profile?.id })
+ const response = await createContent({ projectRef: ref, payload })
+ const snippetId = response.content[0].id
+ router.push(`/project/${ref}/sql/${snippetId}`)
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to create new query: ${error.message}`,
+ })
+ }
+ }
return (
<div className="mt-6">
@@ -170,17 +87,19 @@ const SideBarContent = observer(() => {
block
icon={<IconPlus />}
type="default"
+ disabled={isLoading}
style={{ justifyContent: 'start' }}
onClick={() => handleNewQuery()}
>
New query
</Button>
<Input
+ size="tiny"
icon={<IconSearch size="tiny" />}
placeholder="Search"
+ disabled={isLoading}
onChange={(e) => setFilterString(e.target.value)}
value={filterString}
- size="tiny"
actions={
filterString && (
<IconX
@@ -193,28 +112,22 @@ const SideBarContent = observer(() => {
/>
</div>
)}
-
- {(sqlEditorStore?.tabs ?? []).length === 0 ? (
- <div className="my-4 flex items-center space-x-2 px-7">
- <IconLoader className="animate-spin" size={16} strokeWidth={2} />
- <p className="text-sm">Loading SQL snippets</p>
+ {isLoading ? (
+ <div className="px-5 my-4 space-y-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
</div>
- ) : (
+ ) : isSuccess ? (
<div className="space-y-6">
{IS_PLATFORM && (
<div className="px-3">
<Menu.Group title="Getting started" />
- {getStartedTabs.map((tab: any) => {
- const { id, name } = tab || {}
- return (
- <ProductMenuItem
- key={id}
- name={name}
- isActive={sqlEditorStore.activeTab.id === id}
- onClick={() => sqlEditorStore.selectTab(id)}
- />
- )
- })}
+ <ProductMenuItem
+ name="Welcome"
+ isActive={id === undefined}
+ url={`/project/${ref}/sql`}
+ />
</div>
)}
<div className="space-y-6 px-3">
@@ -225,7 +138,7 @@ const SideBarContent = observer(() => {
{favouriteTabs.map((tabInfo: any) => {
const { id } = tabInfo || {}
return (
- <OpenQueryItem
+ <QueryItem
key={id}
tabInfo={tabInfo}
canCreateSQLSnippet={canCreateSQLSnippet}
@@ -242,7 +155,7 @@ const SideBarContent = observer(() => {
{queryTabs.map((tabInfo: any) => {
const { id } = tabInfo || {}
return (
- <OpenQueryItem
+ <QueryItem
key={id}
tabInfo={tabInfo}
canCreateSQLSnippet={canCreateSQLSnippet}
@@ -259,6 +172,8 @@ const SideBarContent = observer(() => {
)}
</div>
</div>
+ ) : (
+ <div></div>
)}
</Menu>
</div>
diff --git a/studio/components/to-be-cleaned/SqlEditor/RenameQuery.js b/studio/components/to-be-cleaned/SqlEditor/RenameQuery.js
deleted file mode 100644
index 91b092168ac..00000000000
--- a/studio/components/to-be-cleaned/SqlEditor/RenameQuery.js
+++ /dev/null
@@ -1,94 +0,0 @@
-import React from 'react'
-import { observer } from 'mobx-react-lite'
-
-import { useStore } from 'hooks'
-import { useSqlStore } from 'localStores/sqlEditor/SqlEditorStore'
-import { Button, Form, Input, Modal } from 'ui'
-
-const RenameQuery = observer(({ tabId, onComplete, visible, onCancel }) => {
- const { ui, content: contentStore } = useStore()
-
- const sqlEditorStore = useSqlStore()
- const model = prepareModel()
-
- function prepareModel() {
- const tabInfo = sqlEditorStore.tabs.find((x) => x.id === tabId)
- if (tabInfo) return tabInfo.renameModel
-
- const favInfo = sqlEditorStore.favorites.find((x) => x.key === tabId)
- if (favInfo) return favInfo.renameModel
- }
-
- async function onRename(model) {
- try {
- /*
- * new main db save
- */
- await contentStore.update(tabId, {
- name: model.name,
- description: model.desc,
- })
-
- /*
- * old localStorage save
- */
- sqlEditorStore.renameQuery(tabId, model)
-
- if (onComplete) onComplete()
- return Promise.resolve()
- } catch (error) {
- ui.setNotification({
- error,
- category: 'error',
- message: `Failed to rename query: ${error.message}`,
- })
- }
- }
-
- return (
- <Modal visible={visible} onCancel={onCancel} hideFooter header="Rename" size="small">
- <Form
- onReset={onCancel}
- validateOnBlur
- initialValues={{
- name: model ? model.name : '',
- desc: model ? model.desc : '',
- }}
- validate={(values) => {
- const errors = {}
- if (!values.name) errors.name = 'Please enter a query name'
- return errors
- }}
- onSubmit={async (values, { setSubmitting }) => {
- setSubmitting(true)
- await onRename(values)
- setSubmitting(false)
- }}
- >
- {({ isSubmitting }) => (
- <div className="space-y-4 py-4">
- <Modal.Content>
- <Input label="Name" id="name" name="name" />
- </Modal.Content>
- <Modal.Content>
- <Input label="Description" id="desc" placeholder="Describe query" />
- </Modal.Content>
- <Modal.Separator />
- <Modal.Content>
- <div className="flex items-center justify-end gap-2">
- <Button htmlType="reset" type="default" onClick={onCancel}>
- Cancel
- </Button>
- <Button htmlType="submit" loading={isSubmitting}>
- Rename query
- </Button>
- </div>
- </Modal.Content>
- </div>
- )}
- </Form>
- </Modal>
- )
-})
-
-export default RenameQuery
diff --git a/studio/components/to-be-cleaned/SqlEditor/SqlEditor.constants.ts b/studio/components/to-be-cleaned/SqlEditor/SqlEditor.constants.ts
deleted file mode 100644
index c8b9ae578e4..00000000000
--- a/studio/components/to-be-cleaned/SqlEditor/SqlEditor.constants.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { SqlSnippets, UserContent } from 'types'
-
-export const SQL_SNIPPET_SCHEMA_VERSION = '1.0'
-
-export const NEW_SQL_SNIPPET_SKELETON: UserContent<SqlSnippets.Content> = {
- name: 'New Query',
- description: '',
- type: 'sql',
- visibility: 'user', // default to user scope
- content: {
- schema_version: SQL_SNIPPET_SCHEMA_VERSION,
- content_id: '',
- sql: 'this is a test',
- favorite: false,
- },
-}
diff --git a/studio/components/to-be-cleaned/SqlEditor/SqlEditor.utils.ts b/studio/components/to-be-cleaned/SqlEditor/SqlEditor.utils.ts
deleted file mode 100644
index 7ba8d40a516..00000000000
--- a/studio/components/to-be-cleaned/SqlEditor/SqlEditor.utils.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { SqlSnippets, UserContent } from 'types'
-import { NEW_SQL_SNIPPET_SKELETON } from './SqlEditor.constants'
-
-export const createSqlSnippetSkeleton = ({
- name,
- sql,
- owner_id,
-}: {
- name?: string
- sql?: string
- owner_id?: number
-} = {}): UserContent<SqlSnippets.Content> => {
- return {
- ...NEW_SQL_SNIPPET_SKELETON,
- ...(name && { name }),
- ...(owner_id && { owner_id }),
- content: {
- ...NEW_SQL_SNIPPET_SKELETON.content,
- content_id: '',
- sql: sql ?? '',
- },
- }
-}
diff --git a/studio/components/to-be-cleaned/SqlEditor/TabSqlQuery.js b/studio/components/to-be-cleaned/SqlEditor/TabSqlQuery.js
deleted file mode 100644
index 4c16b6571b7..00000000000
--- a/studio/components/to-be-cleaned/SqlEditor/TabSqlQuery.js
+++ /dev/null
@@ -1,448 +0,0 @@
-import Split from 'react-split'
-import Editor from '@monaco-editor/react'
-import DataGrid from '@supabase/react-data-grid'
-import classNames from 'classnames'
-import { CSVLink } from 'react-csv'
-import { debounce } from 'lodash'
-import { observer } from 'mobx-react-lite'
-import { useEffect, useRef, useState } from 'react'
-import { Button, Dropdown, IconCheck, IconChevronDown, IconClipboard } from 'ui'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-
-import { useKeyboardShortcuts, useStore, useWindowDimensions, checkPermissions } from 'hooks'
-import Telemetry from 'lib/telemetry'
-import { copyToClipboard, timeout } from 'lib/helpers'
-import { useProfileQuery } from 'data/profile/profile-query'
-import { useSqlStore, UTILITY_TAB_TYPES } from 'localStores/sqlEditor/SqlEditorStore'
-import { SQL_SNIPPET_SCHEMA_VERSION } from './SqlEditor.constants'
-import UtilityActions from 'components/interfaces/SQLEditor/TabSqlQuery/UtilityActions'
-
-const TabSqlQuery = observer(() => {
- const sqlEditorStore = useSqlStore()
- const { data: profile } = useProfileQuery()
- const { content: contentStore } = useStore()
- const { height: screenHeight } = useWindowDimensions()
-
- const snapOffset = 50
- const minSize = 44
- const tabMenuHeight = 44
- const offset = 3
-
- const canCreateSQLSnippet = checkPermissions(PermissionAction.CREATE, 'user_content', {
- resource: { type: 'sql', owner_id: profile?.id },
- subject: { id: profile?.id },
- })
-
- useEffect(() => {
- // minus fixed tabMenu height
- const utilityPanelHeight =
- (parseFloat(screenHeight - tabMenuHeight) * sqlEditorStore.activeTab.splitSizes[1]) / 100
- if (utilityPanelHeight - snapOffset < minSize) {
- sqlEditorStore.activeTab.resizeUtilityTab(0)
- } else {
- sqlEditorStore.activeTab.resizeUtilityTab(utilityPanelHeight - minSize - offset)
- }
- }, [screenHeight, sqlEditorStore.activeTab.splitSizes])
-
- function onDragEnd(sizes) {
- sqlEditorStore.activeTab.setSplitSizes(sizes)
- }
-
- async function updateSqlSnippet(value) {
- if (!canCreateSQLSnippet) return
-
- if (sqlEditorStore.activeTab) {
- await contentStore.updateSql(sqlEditorStore.activeTab.id, {
- content: {
- schema_version: SQL_SNIPPET_SCHEMA_VERSION,
- content_id: sqlEditorStore.activeTab.id,
- sql: value,
- favorite: sqlEditorStore.activeTab.favorite,
- },
- })
- } else {
- console.warn('No active tab found while updating SQL snippet')
- }
- }
-
- return (
- <div className="flex h-full flex-col">
- <Split
- style={{ height: '100%' }}
- direction="vertical"
- gutterSize={2}
- sizes={sqlEditorStore.activeTab.splitSizes || []}
- minSize={minSize}
- snapOffset={snapOffset}
- expandToMin={true}
- collapsed={sqlEditorStore.activeTab.utilityTabHeight == 0 ? 1 : undefined}
- onDragEnd={onDragEnd}
- >
- <MonacoEditor
- error={sqlEditorStore.activeTab.sqlQueryError}
- updateSqlSnippet={updateSqlSnippet}
- setUpdatingRequired={contentStore.setUpdatingRequired.bind(contentStore)}
- />
- <div>
- <UtilityPanel updateSqlSnippet={updateSqlSnippet} />
- </div>
- </Split>
- </div>
- )
-})
-export default TabSqlQuery
-
-const MonacoEditor = ({ error, updateSqlSnippet, setUpdatingRequired }) => {
- const sqlEditorStore = useSqlStore()
- const editorRef = useRef(null)
- const monacoRef = useRef(null)
-
- useEffect(() => {
- if (!editorRef.current || !monacoRef.current) return
-
- if (!error) {
- const model = editorRef.current.getModel()
- monacoRef.current.editor.setModelMarkers(model, 'owner', [])
- } else if (error?.cursorPosition) {
- const model = editorRef.current.getModel()
- const position = model.getPositionAt(error.cursorPosition)
- monacoRef.current.editor.setModelMarkers(model, 'owner', [
- {
- startLineNumber: position.lineNumber,
- endLineNumber: 1,
- startColumn: position.column,
- endColumn: 0,
- message: error.message || 'syntax error',
- severity: monacoRef.current.MarkerSeverity.Error,
- },
- ])
- }
- }, [error])
-
- useEffect(() => {
- if (editorRef.current) {
- // add margin above first line
- editorRef.current?.changeViewZones((accessor) => {
- accessor.addZone({
- afterLineNumber: 0,
- heightInPx: 4,
- domNode: document.createElement('div'),
- })
- })
- }
- }, [sqlEditorStore.activeTab.id])
-
- async function handleEditorOnMount(editor, monaco) {
- editorRef.current = editor
- monacoRef.current = monaco
-
- editor.addAction({
- id: 'supabase',
- label: 'Run Query',
- keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.Enter],
- contextMenuGroupId: 'operation',
- contextMenuOrder: 0,
- run: async () => {
- if (sqlEditorStore.isExecuting) return
-
- const selectedValue = (editorRef?.current)
- .getModel()
- .getValueInRange(editorRef?.current?.getSelection())
-
- await sqlEditorStore.startExecuting(selectedValue)
-
- // onInputRun(selectedValue || (editorRef?.current as any)?.getValue())
- },
- })
-
- // add margin above first line
- editor.changeViewZones((accessor) => {
- accessor.addZone({
- afterLineNumber: 0,
- heightInPx: 4,
- domNode: document.createElement('div'),
- })
- })
-
- // when editor did mount, it will need a delay before focus() works properly
- await timeout(500)
- editor?.focus()
- }
-
- // changes are stored in debouncer before running persistData()
- let debounceUpdateSqlSnippet = debounce((value) => updateSqlSnippet(value), 1500)
-
- async function handleEditorChange(value) {
- // update sqlEditorStore with new value immediately
- // this is so any SQL run will be whatever is currently in monaco editor
- sqlEditorStore.activeTab.setQuery(value)
-
- // inform the content store that the SQL has changed and needs to be persisted
- // this is so we can block the tab being closed if an update is required
- setUpdatingRequired?.()
-
- // debounce changes
- debounceUpdateSqlSnippet(value)
- }
-
- return (
- <div className="flex-grow overflow-y-auto border-b dark:border-dark">
- <Editor
- className="monaco-editor"
- theme={'supabase'}
- onMount={handleEditorOnMount}
- onChange={handleEditorChange}
- defaultLanguage="pgsql"
- defaultValue={sqlEditorStore.activeTab.query}
- path={sqlEditorStore.activeTab.id}
- options={{
- tabSize: 2,
- fontSize: 13,
- minimap: {
- enabled: false,
- },
- wordWrap: 'on',
- fixedOverflowWidgets: true,
- }}
- />
- </div>
- )
-}
-
-const UtilityPanel = observer(({ updateSqlSnippet }) => {
- const sqlEditorStore = useSqlStore()
-
- return (
- <>
- <div className="flex justify-between overflow-visible px-6 py-2">
- <ResultsDropdown />
- <div className="inline-flex items-center justify-end">
- <UtilityActions updateSqlSnippet={updateSqlSnippet} />
- </div>
- </div>
- <div className="p-0 pt-0 pb-0">
- {sqlEditorStore.activeTab.activeUtilityTab == UTILITY_TAB_TYPES.RESULTS && (
- <UtilityTabResults />
- )}
- </div>
- </>
- )
-})
-
-const ResultsDropdown = observer(() => {
- const { ui } = useStore()
- const sqlEditorStore = useSqlStore()
- const csvRef = useRef(null)
-
- function onDownloadCSV() {
- csvRef.current?.link.click()
- Telemetry.sendEvent(
- { category: 'sql_editor', action: 'sql_download_csv', label: '' },
- ui.googleAnalyticsProps
- )
- }
-
- function onCopyAsMarkdown() {
- if (navigator) {
- copyToClipboard(sqlEditorStore.activeTab.markdownData, () => {
- ui.setNotification({ category: 'success', message: 'Copied results to clipboard' })
- Telemetry.sendEvent(
- { category: 'sql_editor', action: 'sql_copy_as_markdown', label: '' },
- ui.googleAnalyticsProps
- )
- })
- }
- }
-
- const formatDataForCSV = (data = []) => {
- return data.map((row) => {
- const formattedRow = { ...row }
- Object.keys(row).forEach((key) => {
- if (typeof row[key] === 'object') formattedRow[key] = JSON.stringify(row[key])
- })
- return formattedRow
- })
- }
-
- return (
- <Dropdown
- side="bottom"
- align="start"
- overlay={
- <>
- <Dropdown.Item onClick={onDownloadCSV}>Download CSV</Dropdown.Item>
- <Dropdown.Item onClick={onCopyAsMarkdown}>Copy as markdown</Dropdown.Item>
- </>
- }
- >
- <Button as="span" type="text" iconRight={<IconChevronDown />}>
- Results
- </Button>
- <CSVLink
- ref={csvRef}
- className="hidden"
- data={formatDataForCSV(sqlEditorStore.activeTab?.csvData || '')}
- filename={`supabase_${sqlEditorStore.projectRef}_${sqlEditorStore.activeTab.name}`}
- />
- </Dropdown>
- )
-})
-
-const UtilityTabResults = observer(() => {
- const sqlEditorStore = useSqlStore()
-
- if (sqlEditorStore.activeTab.utilityTabHeight == 0) return null
- if (sqlEditorStore.activeTab.isExecuting) {
- return (
- <div className="bg-table-header-light dark:bg-table-header-dark">
- <p className="m-0 border-0 px-6 py-4 font-mono text-sm">Running...</p>
- </div>
- )
- } else if (sqlEditorStore.activeTab.errorResult) {
- return (
- <div className="bg-table-header-light dark:bg-table-header-dark">
- <p className="m-0 border-0 px-6 py-4 font-mono">{sqlEditorStore.activeTab.errorResult}</p>
- </div>
- )
- } else if (sqlEditorStore.activeTab.hasNoResult) {
- return (
- <div className="bg-table-header-light dark:bg-table-header-dark">
- <p className="m-0 border-0 px-6 py-4 text-sm text-scale-1000">
- Click <code>RUN</code> or hit{' '}
- <code>{window.navigator.platform.match(/^Mac/) ? '⌘' : 'Ctrl'} + Enter</code> to execute
- your query.
- </p>
- </div>
- )
- }
-
- return (
- <div style={{ height: sqlEditorStore.activeTab.utilityTabHeight }}>
- <Results results={sqlEditorStore.activeTab.results} />
- </div>
- )
-})
-
-const Results = ({ results }) => {
- const [cellPosition, setCellPosition] = useState(undefined)
- const [copiedCell, setCopiedCell] = useState(undefined)
-
- useKeyboardShortcuts(
- {
- 'Command+c': (event) => {
- event.stopPropagation()
- onCopySelectedCell()
- },
- 'Control+c': (event) => {
- event.stopPropagation()
- onCopySelectedCell()
- },
- },
- ['INPUT', 'TEXTAREA']
- )
-
- useEffect(() => {
- let timeoutId = 0
-
- if (copiedCell) {
- timeoutId = setTimeout(() => {
- setCopiedCell(undefined)
- }, 1000)
- }
-
- return () => {
- // we need to clear previous timeout to prevent checkmark flickering
- // when clicking `Copy` button multiple times in a short time
- timeoutId && clearTimeout(timeoutId)
- }
- }, [copiedCell])
-
- if (results?.error) {
- return (
- <div className="bg-table-header-light dark:bg-table-header-dark">
- <p className="m-0 border-0 px-6 py-4 font-mono text-scale-1000">ERROR: {results.error}</p>
- </div>
- )
- }
- if (!results.length) {
- return (
- <div className="bg-table-header-light dark:bg-table-header-dark">
- <p className="m-0 border-0 px-6 py-4 font-mono text-sm">Success. No rows returned</p>
- </div>
- )
- }
-
- const handleCopyClick = (column, row, rowIndex) => {
- copyToClipboard(formatClipboardValue(row[column]), () => {
- setCopiedCell(`${column},${rowIndex}`)
- })
- }
-
- const formatter = (column, row, rowIndex) => {
- const isCopied = copiedCell === `${column},${rowIndex}`
-
- return (
- <div className="group sb-grid-select-cell__formatter overflow-hidden">
- <span className="font-mono text-xs truncate">{JSON.stringify(row[column])}</span>
-
- {row[column] != undefined && (
- <Button
- type="outline"
- icon={isCopied ? <IconCheck size="tiny" /> : <IconClipboard size="tiny" />}
- onClick={() => handleCopyClick(column, row, rowIndex)}
- className={classNames(
- 'mx-1 group-hover:block group-hover:opacity-50 hover:opacity-100',
- !isCopied && 'hidden'
- )}
- title="Copy"
- />
- )}
- </div>
- )
- }
- const columnRender = (name) => {
- return <div className="flex h-full items-center justify-center font-mono">{name}</div>
- }
- const columns = Object.keys(results[0]).map((key) => ({
- key,
- name: key,
- formatter: ({ row }) => formatter(key, row, results.indexOf(row)),
- headerRenderer: () => columnRender(key),
- resizable: true,
- width: 120,
- }))
-
- function onSelectedCellChange(position) {
- setCellPosition(position)
- }
-
- function onCopySelectedCell() {
- if (columns && cellPosition) {
- const { idx, rowIdx } = cellPosition
- const column = columns[idx]
- if (!column) return
-
- const colKey = column.key
- const cellValue = results[rowIdx]?.[colKey] ?? ''
- const value = formatClipboardValue(cellValue)
- copyToClipboard(value)
- }
- }
-
- return (
- <DataGrid
- columns={columns}
- rows={results}
- style={{ height: '100%' }}
- onSelectedCellChange={onSelectedCellChange}
- />
- )
-}
-
-function formatClipboardValue(value) {
- if (value === null) return ''
- if (typeof value == 'object' || Array.isArray(value)) {
- return JSON.stringify(value)
- }
- return value
-}
diff --git a/studio/components/to-be-cleaned/SqlEditor/TabWelcome.js b/studio/components/to-be-cleaned/SqlEditor/TabWelcome.js
deleted file mode 100644
index 5ca96a1c348..00000000000
--- a/studio/components/to-be-cleaned/SqlEditor/TabWelcome.js
+++ /dev/null
@@ -1,109 +0,0 @@
-import { useState } from 'react'
-import { partition } from 'lodash'
-import { observer } from 'mobx-react-lite'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-
-import Telemetry from 'lib/telemetry'
-import { useOptimisticSqlSnippetCreate, checkPermissions, useStore } from 'hooks'
-import { useProfileQuery } from 'data/profile/profile-query'
-import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.constants'
-import CardButton from 'components/ui/CardButton'
-
-const TabWelcome = observer(() => {
- const { ui } = useStore()
- const { data: profile } = useProfileQuery()
- const [sql, quickStart] = partition(SQL_TEMPLATES, { type: 'template' })
- const canCreateSQLSnippet = checkPermissions(PermissionAction.CREATE, 'user_content', {
- resource: { type: 'sql', owner_id: profile?.id },
- subject: { id: profile?.id },
- })
- const handleNewQuery = useOptimisticSqlSnippetCreate(canCreateSQLSnippet)
-
- return (
- <div className="block h-full space-y-8 overflow-y-auto p-6">
- <div>
- <div className="mb-4">
- <h1 className="text-scale-1200 mb-3 text-xl">Scripts</h1>
- <p className="text-scale-1100 text-sm">Quick scripts to run on your database.</p>
- <p className="text-scale-1100 text-sm">
- Click on any script to fill the query box, modify the script, then click
- <span className="text-code">Run</span>.
- </p>
- </div>
- <div className="grid gap-4 sm:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
- {sql.map((x) => (
- <SqlCard
- key={x.title}
- title={x.title}
- description={x.description}
- sql={x.sql}
- onClick={(sql, title) => {
- handleNewQuery({ sql, name: title })
- Telemetry.sendEvent(
- {
- category: 'scripts',
- action: 'script_clicked',
- label: x.title,
- },
- ui.googleAnalyticsProps
- )
- }}
- />
- ))}
- </div>
- </div>
- <div className="mb-8">
- <div className="mb-4">
- <h1 className="text-scale-1200 mb-3 text-xl">Quick start</h1>
- <p className="text-scale-1100 text-sm">
- While we're in beta, we want to offer a quick way to explore Supabase. While we build
- importers, check out these simple starters.
- </p>
- <p className="text-scale-1100 text-sm">
- Click on any script to fill the query box, modify the script, then click
- <span className="text-code">Run</span>.
- </p>
- </div>
- <div className="grid gap-4 sm:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
- {quickStart.map((x) => (
- <SqlCard
- key={x.title}
- title={x.title}
- description={x.description}
- sql={x.sql}
- onClick={(sql, title) => {
- handleNewQuery({ sql, name: title })
- Telemetry.sendEvent(
- {
- category: 'quickstart',
- action: 'quickstart_clicked',
- label: x.title,
- },
- ui.googleAnalyticsProps
- )
- }}
- />
- ))}
- </div>
- </div>
- </div>
- )
-})
-
-export default TabWelcome
-
-const SqlCard = ({ title, description, sql, onClick }) => {
- const [loading, setLoading] = useState(false)
-
- function handleOnClick() {
- setLoading(true)
- onClick(sql, title)
- }
- return (
- <CardButton
- onClick={() => handleOnClick()}
- title={title}
- footer={<span className="text-scale-1100 text-sm">{description}</span>}
- />
- )
-}
diff --git a/studio/components/ui/CardButton.tsx b/studio/components/ui/CardButton.tsx
index f80f78d5bc2..c5bf21833bf 100644
--- a/studio/components/ui/CardButton.tsx
+++ b/studio/components/ui/CardButton.tsx
@@ -1,5 +1,5 @@
import React, { FC } from 'react'
-import { IconChevronRight } from 'ui'
+import { IconChevronRight, IconLoader } from 'ui'
import Link from 'next/link'
interface Props {
@@ -14,6 +14,7 @@ interface Props {
onClick?: () => void
icon?: React.ReactNode
containerHeightClassName?: string
+ loading?: boolean
}
const CardButton: FC<Props> = ({
@@ -28,6 +29,7 @@ const CardButton: FC<Props> = ({
onClick,
icon,
containerHeightClassName = 'h-32',
+ loading = false,
}) => {
const LinkContainer = ({ children }: { children: React.ReactNode }) => (
<Link href={linkHref}>
@@ -104,7 +106,7 @@ const CardButton: FC<Props> = ({
group-hover:text-scale-1200
"
>
- <IconChevronRight />
+ {loading ? <IconLoader className="animate-spin" /> : <IconChevronRight />}
</div>
)}
</div>
diff --git a/studio/data/content/content-create-mutation.ts b/studio/data/content/content-create-mutation.ts
new file mode 100644
index 00000000000..a7235fd70ec
--- /dev/null
+++ b/studio/data/content/content-create-mutation.ts
@@ -0,0 +1,48 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { post } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { UserContent } from 'types'
+import { contentKeys } from './keys'
+
+type CreateContentVariables = {
+ projectRef: string
+ payload: UserContent
+}
+
+export async function createContent(
+ { projectRef, payload }: CreateContentVariables,
+ signal?: AbortSignal
+) {
+ const response = await post<UserContent[]>(`${API_URL}/projects/${projectRef}/content`, payload, {
+ signal,
+ })
+
+ if (response.error) throw response.error
+ return { content: response }
+}
+
+type CreateContentData = Awaited<ReturnType<typeof createContent>>
+
+export const useContentCreateMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<CreateContentData, unknown, CreateContentVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<CreateContentData, unknown, CreateContentVariables>(
+ (args) => createContent(args),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+
+ await Promise.all([queryClient.invalidateQueries(contentKeys.list(projectRef))])
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/data/content/content-delete-mutation.ts b/studio/data/content/content-delete-mutation.ts
new file mode 100644
index 00000000000..14653436e14
--- /dev/null
+++ b/studio/data/content/content-delete-mutation.ts
@@ -0,0 +1,47 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { delete_ } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { UserContent } from 'types'
+import { contentKeys } from './keys'
+
+type DeleteContentVariables = { projectRef: string; id: string }
+
+export async function deleteContent(
+ { projectRef, id }: DeleteContentVariables,
+ signal?: AbortSignal
+) {
+ const response = await delete_<UserContent>(
+ `${API_URL}/projects/${projectRef}/content?id=${id}`,
+ undefined,
+ { signal }
+ )
+
+ if (response.error) throw response.error
+ return response
+}
+
+type DeleteContentData = Awaited<ReturnType<typeof deleteContent>>
+
+export const useContentDeleteMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<DeleteContentData, unknown, DeleteContentVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<DeleteContentData, unknown, DeleteContentVariables>(
+ (args) => deleteContent(args),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+
+ await Promise.all([queryClient.invalidateQueries(contentKeys.list(projectRef))])
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/data/content/content-query.ts b/studio/data/content/content-query.ts
new file mode 100644
index 00000000000..364e7499b43
--- /dev/null
+++ b/studio/data/content/content-query.ts
@@ -0,0 +1,86 @@
+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { useCallback } from 'react'
+import { Dashboards, LogSqlSnippets, Owner, SqlSnippets } from 'types'
+import { contentKeys } from './keys'
+
+type ContentBase = {
+ id?: string
+ name: string
+ description?: string
+ visibility: 'user' | 'project' | 'org' | 'public'
+ owner_id?: number // user id
+ last_updated_by?: number // user id
+ inserted_at?: string // '2021-08-26T08:24:52.040695+00:00'
+ owner?: Owner
+ project_id?: number
+ updated_at?: string // '2021-08-26T08:24:52.040695+00:00'
+ updated_by?: Owner
+}
+
+export type Content = ContentBase &
+ (
+ | {
+ type: 'sql'
+ content: SqlSnippets.Content
+ }
+ | {
+ type: 'report'
+ content: Dashboards.Content
+ }
+ | {
+ type: 'log_sql'
+ content: LogSqlSnippets.Content
+ }
+ )
+
+export async function getContent(
+ projectRef: string | undefined,
+ signal?: AbortSignal
+): Promise<{
+ content: Content[]
+}> {
+ if (typeof projectRef === 'undefined') {
+ throw new Error('projectRef is required for getContent')
+ }
+
+ let response = await get(`${API_URL}/projects/${projectRef}/content`, { signal })
+
+ if (response.error) {
+ throw response.error
+ }
+
+ if (!response) {
+ throw new Error('Content not found')
+ }
+
+ return {
+ content: response.data,
+ }
+}
+
+export type ContentData = Awaited<ReturnType<typeof getContent>>
+export type ContentError = unknown
+
+export const useContentQuery = <TData = ContentData>(
+ projectRef: string | undefined,
+ { enabled = true, ...options }: UseQueryOptions<ContentData, ContentError, TData> = {}
+) =>
+ useQuery<ContentData, ContentError, TData>(
+ contentKeys.list(projectRef),
+ ({ signal }) => getContent(projectRef, signal),
+ { enabled: enabled && typeof projectRef !== 'undefined', ...options }
+ )
+
+export const useContentPrefetch = (projectRef: string | undefined) => {
+ const client = useQueryClient()
+
+ return useCallback(() => {
+ if (projectRef) {
+ client.prefetchQuery(contentKeys.list(projectRef), ({ signal }) =>
+ getContent(projectRef, signal)
+ )
+ }
+ }, [projectRef])
+}
diff --git a/studio/data/content/content-update-mutation.ts b/studio/data/content/content-update-mutation.ts
new file mode 100644
index 00000000000..111915077ba
--- /dev/null
+++ b/studio/data/content/content-update-mutation.ts
@@ -0,0 +1,53 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { patch } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { UserContent } from 'types'
+import { contentKeys } from './keys'
+
+type UpdateContentVariables = {
+ projectRef: string
+ id: string
+ content: Partial<UserContent>
+}
+
+export async function updateContent(
+ { projectRef, id, content }: UpdateContentVariables,
+ signal?: AbortSignal
+) {
+ const created = await patch<UserContent>(
+ `${API_URL}/projects/${projectRef}/content?id=${id}`,
+ content,
+ { signal }
+ )
+ if (created.error) {
+ throw created.error
+ }
+
+ return { content: created }
+}
+
+type UpdateContentData = Awaited<ReturnType<typeof updateContent>>
+
+export const useContentUpdateMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<UpdateContentData, unknown, UpdateContentVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<UpdateContentData, unknown, UpdateContentVariables>(
+ (args) => updateContent(args),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+
+ await Promise.all([queryClient.invalidateQueries(contentKeys.list(projectRef))])
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/data/content/keys.ts b/studio/data/content/keys.ts
new file mode 100644
index 00000000000..bf8ad71d362
--- /dev/null
+++ b/studio/data/content/keys.ts
@@ -0,0 +1,3 @@
+export const contentKeys = {
+ list: (projectRef: string | undefined) => ['projects', projectRef, 'content'] as const,
+}
diff --git a/studio/data/content/sql-snippets-query.ts b/studio/data/content/sql-snippets-query.ts
new file mode 100644
index 00000000000..9cb904776b9
--- /dev/null
+++ b/studio/data/content/sql-snippets-query.ts
@@ -0,0 +1,25 @@
+import { UseQueryOptions } from '@tanstack/react-query'
+import { Content, ContentData, ContentError, useContentQuery } from 'data/content/content-query'
+
+export type SqlSnippet = Extract<Content, { type: 'sql' }>
+
+export type SqlSnippets = {
+ snippets: SqlSnippet[]
+}
+
+function filterSqlContent(content: Content): content is Extract<Content, { type: 'sql' }> {
+ return content.type === 'sql'
+}
+
+export const useSqlSnippetsQuery = (
+ projectRef: string | undefined,
+ options: UseQueryOptions<ContentData, ContentError, SqlSnippets> = {}
+) =>
+ useContentQuery<SqlSnippets>(projectRef, {
+ select: (data) => {
+ return {
+ snippets: data.content.filter(filterSqlContent),
+ }
+ },
+ ...options,
+ })
diff --git a/studio/data/database/schemas-query.ts b/studio/data/database/schemas-query.ts
new file mode 100644
index 00000000000..b8b89e03b1d
--- /dev/null
+++ b/studio/data/database/schemas-query.ts
@@ -0,0 +1,60 @@
+import { useCallback } from 'react'
+import { UseQueryOptions } from '@tanstack/react-query'
+import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query'
+
+export type Schema = {
+ name: string
+}
+
+export const getSchemasQuery = () => {
+ const sql = /* SQL */ `
+ SELECT nspname as name
+ FROM pg_namespace
+ WHERE
+ nspname not in ('information_schema', 'pg_catalog', 'pg_toast')
+ AND nspname not like 'pg_temp_%'
+ AND nspname not like 'pg_toast_temp_%'
+ AND has_schema_privilege(oid, 'CREATE, USAGE')
+ ORDER BY nspname;
+`.trim()
+
+ return sql
+}
+
+export type SchemasVariables = {
+ projectRef?: string
+ connectionString?: string
+}
+
+export type SchemasData = Schema[]
+export type SchemasError = unknown
+
+export const useSchemasQuery = <TData extends SchemasData = SchemasData>(
+ { projectRef, connectionString }: SchemasVariables,
+ options: UseQueryOptions<ExecuteSqlData, SchemasError, TData> = {}
+) => {
+ return useExecuteSqlQuery(
+ {
+ projectRef,
+ connectionString,
+ sql: getSchemasQuery(),
+ queryKey: ['schemas'],
+ },
+ options
+ )
+}
+
+export const useSchemasPrefetch = () => {
+ const prefetch = useExecuteSqlPrefetch()
+
+ return useCallback(
+ ({ projectRef, connectionString }: SchemasVariables) =>
+ prefetch({
+ projectRef,
+ connectionString,
+ sql: getSchemasQuery(),
+ queryKey: ['schemas'],
+ }),
+ [prefetch]
+ )
+}
diff --git a/studio/data/database/table-columns-query.ts b/studio/data/database/table-columns-query.ts
new file mode 100644
index 00000000000..64f12c4bf83
--- /dev/null
+++ b/studio/data/database/table-columns-query.ts
@@ -0,0 +1,112 @@
+import { useCallback } from 'react'
+import { UseQueryOptions } from '@tanstack/react-query'
+import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query'
+
+export type TableColumn = {
+ schema: string
+ table: string
+ name: string
+ isTable: boolean
+ columns: any[]
+}
+
+export const getTableColumnsQuery = () => {
+ const sql = /* SQL */ `
+ SELECT
+ tbl.schemaname as schema,
+ tbl.tablename as table,
+ tbl.quoted_name as name,
+ tbl.is_table as isTable,
+ json_agg(a) as columns
+ FROM
+ (
+ SELECT
+ n.nspname as schemaname,
+ c.relname as tablename,
+ (quote_ident(n.nspname) || '.' || quote_ident(c.relname)) as quoted_name,
+ true as is_table
+ FROM
+ pg_catalog.pg_class c
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
+ WHERE
+ c.relkind = 'r'
+ AND n.nspname not in ('information_schema', 'pg_catalog', 'pg_toast')
+ AND n.nspname not like 'pg_temp_%'
+ AND n.nspname not like 'pg_toast_temp_%'
+ AND has_schema_privilege(n.oid, 'USAGE') = true
+ AND has_table_privilege(quote_ident(n.nspname) || '.' || quote_ident(c.relname), 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER') = true
+ union all
+ SELECT
+ n.nspname as schemaname,
+ c.relname as tablename,
+ (quote_ident(n.nspname) || '.' || quote_ident(c.relname)) as quoted_name,
+ false as is_table
+ FROM
+ pg_catalog.pg_class c
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
+ WHERE
+ c.relkind in ('v', 'm')
+ AND n.nspname not in ('information_schema', 'pg_catalog', 'pg_toast')
+ AND n.nspname not like 'pg_temp_%'
+ AND n.nspname not like 'pg_toast_temp_%'
+ AND has_schema_privilege(n.oid, 'USAGE') = true
+ AND has_table_privilege(quote_ident(n.nspname) || '.' || quote_ident(c.relname), 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER') = true
+ ) as tbl
+ LEFT JOIN (
+ SELECT
+ attrelid,
+ attname,
+ format_type(atttypid, atttypmod) as data_type,
+ attnum,
+ attisdropped
+ FROM
+ pg_attribute
+ ) as a ON (
+ a.attrelid = tbl.quoted_name::regclass
+ AND a.attnum > 0
+ AND NOT a.attisdropped
+ AND has_column_privilege(tbl.quoted_name, a.attname, 'SELECT, INSERT, UPDATE, REFERENCES')
+ )
+ GROUP BY schemaname, tablename, quoted_name, is_table;
+`.trim()
+
+ return sql
+}
+
+export type TableColumnsVariables = {
+ projectRef?: string
+ connectionString?: string
+}
+
+export type TableColumnsData = TableColumn[]
+export type TableColumnsError = unknown
+
+export const useTableColumnsQuery = <TData extends TableColumnsData = TableColumnsData>(
+ { projectRef, connectionString }: TableColumnsVariables,
+ options: UseQueryOptions<ExecuteSqlData, TableColumnsError, TData> = {}
+) => {
+ return useExecuteSqlQuery(
+ {
+ projectRef,
+ connectionString,
+ sql: getTableColumnsQuery(),
+ queryKey: ['table-columns'],
+ },
+ options
+ )
+}
+
+export const useTableColumnsPrefetch = () => {
+ const prefetch = useExecuteSqlPrefetch()
+
+ return useCallback(
+ ({ projectRef, connectionString }: TableColumnsVariables) =>
+ prefetch({
+ projectRef,
+ connectionString,
+ sql: getTableColumnsQuery(),
+ queryKey: ['table-columns'],
+ }),
+ [prefetch]
+ )
+}
diff --git a/studio/hooks/deprecated.ts b/studio/hooks/deprecated.ts
index 5e91c0fb2c4..6fe17eb1b94 100644
--- a/studio/hooks/deprecated.ts
+++ b/studio/hooks/deprecated.ts
@@ -121,13 +121,10 @@ function isMounted() {
}
function getWindowDimensions() {
- if (!window) return { width: 0, height: 0 }
+ if (typeof window === 'undefined' || !window) return { width: 0, height: 0 }
const { innerWidth: width, innerHeight: height } = window
- return {
- width,
- height,
- }
+ return { width, height }
}
function useWindowDimensions() {
diff --git a/studio/hooks/misc/useOptimisticSqlSnippetCreate.ts b/studio/hooks/misc/useOptimisticSqlSnippetCreate.ts
index 8791a61ee86..e94d0b1890d 100644
--- a/studio/hooks/misc/useOptimisticSqlSnippetCreate.ts
+++ b/studio/hooks/misc/useOptimisticSqlSnippetCreate.ts
@@ -1,19 +1,29 @@
-import { createSqlSnippetSkeleton } from 'components/to-be-cleaned/SqlEditor/SqlEditor.utils'
+import { createSqlSnippetSkeleton } from 'components/interfaces/SQLEditor/SQLEditor.utils'
import { useProfileQuery } from 'data/profile/profile-query'
import { useSqlStore } from 'localStores/sqlEditor/SqlEditorStore'
import { useCallback } from 'react'
import { useStore } from './useStore'
+import { useContentCreateMutation } from 'data/content/content-create-mutation'
+import { useParams } from 'common'
+import { uuidv4 } from 'lib/helpers'
+
+// [Joshen] Can we not call checkPermissions in here? rather than passing it in as an arg
+// [Joshen] Choosing to deprecate this tbh
export function useOptimisticSqlSnippetCreate(canCreateSQLSnippet: boolean) {
- const { ui, content: contentStore } = useStore()
+ const { ref } = useParams()
const { data: profile } = useProfileQuery()
+ const { ui, content: contentStore } = useStore()
+ const { mutateAsync: createContent } = useContentCreateMutation()
- const sqlEditorStore: any = useSqlStore()
+ // const sqlEditorStore: any = useSqlStore()
return useCallback(
async (args?: Parameters<typeof createSqlSnippetSkeleton>[0]) => {
// get currently selected tab id in case we need to roll back to it
- const previouslySelectedTabId = sqlEditorStore.selectedTabId
+ // const previouslySelectedTabId = sqlEditorStore.selectedTabId
+
+ if (!ref) return console.error('Project ref is required')
const snippet = createSqlSnippetSkeleton({
owner_id: profile?.id,
@@ -21,19 +31,21 @@ export function useOptimisticSqlSnippetCreate(canCreateSQLSnippet: boolean) {
})
// save the snippet in memory in the content store with a client-generated id
- const { data } = contentStore.createOptimistically(snippet)
+ // const { data } = contentStore.createOptimistically(snippet)
+ const data = { ...snippet, id: uuidv4() }
// update the tabs in the sql editor storage to match the content store
- const tabs = sqlEditorStore.tabsFromContentStore(contentStore, profile?.id)
- sqlEditorStore.loadTabs(tabs, false)
+ // const tabs = sqlEditorStore.tabsFromContentStore(contentStore, profile?.id)
+ // sqlEditorStore.loadTabs(tabs, false)
// select tab with new snippet
- sqlEditorStore.selectTab(data.id)
+ // sqlEditorStore.selectTab(data.id)
// save the new query to the server in the background
if (canCreateSQLSnippet) {
- const { error } = await contentStore.save(data)
- if (error) {
+ try {
+ await createContent({ projectRef: ref, payload: data })
+ } catch (error: any) {
ui.setNotification({
category: 'error',
message: `Failed to create new query: ${error.message}`,
@@ -46,6 +58,6 @@ export function useOptimisticSqlSnippetCreate(canCreateSQLSnippet: boolean) {
})
}
},
- [profile, sqlEditorStore, contentStore]
+ [profile, contentStore]
)
}
diff --git a/studio/pages/project/[ref]/sql/[id].tsx b/studio/pages/project/[ref]/sql/[id].tsx
new file mode 100644
index 00000000000..3702e45ae4c
--- /dev/null
+++ b/studio/pages/project/[ref]/sql/[id].tsx
@@ -0,0 +1,93 @@
+import React, { useEffect } from 'react'
+import { observer } from 'mobx-react-lite'
+import { useMonaco } from '@monaco-editor/react'
+import { useSqlStore } from 'localStores/sqlEditor/SqlEditorStore'
+import getPgsqlCompletionProvider from 'components/to-be-cleaned/SqlEditor/PgsqlCompletionProvider'
+import getPgsqlSignatureHelpProvider from 'components/to-be-cleaned/SqlEditor/PgsqlSignatureHelpProvider'
+import { useStore } from 'hooks'
+import { SQLEditorLayout } from 'components/layouts'
+import { NextPageWithLayout } from 'types'
+import { useTheme } from 'common'
+import SQLEditor from 'components/interfaces/SQLEditor/SQLEditor'
+
+const SqlEditor: NextPageWithLayout = () => {
+ const { meta } = useStore()
+ const { isDarkMode } = useTheme()
+ const sqlEditorStore: any = useSqlStore()
+ const monaco = useMonaco()
+
+ useEffect(() => {
+ if (monaco) {
+ monaco.editor.defineTheme('supabase', {
+ base: isDarkMode ? 'vs-dark' : 'vs', // can also be hc-black
+ inherit: true, // can also be false to completely replace the builtin rules
+ rules: [
+ { token: '', background: isDarkMode ? '1f1f1f' : 'f0f0f0' },
+ { token: 'string.sql', foreground: '24b47e' },
+ { token: 'comment', foreground: '666666' },
+ // { token: 'predefined.sql', foreground: 'D4D4D4' },
+ ],
+ colors: {
+ 'editor.background': isDarkMode ? '#1f1f1f' : '#f0f0f0',
+ // 'editorGutter.background': '#30313f',
+ // 'editorLineNumber.foreground': '#555671',
+ },
+ })
+ }
+ }, [monaco, isDarkMode])
+
+ useEffect(() => {
+ if (monaco) {
+ // Enable pgsql format
+ const formatprovider = monaco.languages.registerDocumentFormattingEditProvider('pgsql', {
+ async provideDocumentFormattingEdits(model: any) {
+ const value = model.getValue()
+ const formatted = await formatPgsql(value)
+ return [
+ {
+ range: model.getFullModelRange(),
+ text: formatted,
+ },
+ ]
+ },
+ })
+
+ // register completion item provider for pgsql
+ const completeProvider = monaco.languages.registerCompletionItemProvider(
+ 'pgsql',
+ getPgsqlCompletionProvider(monaco, sqlEditorStore)
+ )
+ const signatureHelpProvider = monaco.languages.registerSignatureHelpProvider(
+ 'pgsql',
+ getPgsqlSignatureHelpProvider(monaco, sqlEditorStore)
+ )
+
+ return () => {
+ formatprovider.dispose()
+ completeProvider.dispose()
+ signatureHelpProvider.dispose()
+ }
+ }
+ }, [monaco])
+
+ async function formatPgsql(value: any) {
+ try {
+ const formatted = await meta.formatQuery(value)
+ if (formatted.error) throw formatted.error
+ return formatted
+ } catch (error) {
+ console.error('formatPgsql error:', error)
+ return value
+ }
+ }
+
+ return (
+ <div className="SQLTabContainer flex-1">
+ <SQLEditor />
+ </div>
+ )
+}
+
+SqlEditor.getLayout = (page) => <SQLEditorLayout title="SQL">{page}</SQLEditorLayout>
+
+export default observer(SqlEditor)
diff --git a/studio/pages/project/[ref]/sql/index.tsx b/studio/pages/project/[ref]/sql/index.tsx
index 3f1407056c2..2de4268bb44 100644
--- a/studio/pages/project/[ref]/sql/index.tsx
+++ b/studio/pages/project/[ref]/sql/index.tsx
@@ -1,107 +1,11 @@
-import React, { useEffect } from 'react'
import { observer } from 'mobx-react-lite'
-import { useMonaco } from '@monaco-editor/react'
-import { useSqlStore, TAB_TYPES } from 'localStores/sqlEditor/SqlEditorStore'
-import TabWelcome from 'components/to-be-cleaned/SqlEditor/TabWelcome'
-import TabSqlQuery from 'components/to-be-cleaned/SqlEditor/TabSqlQuery'
-import getPgsqlCompletionProvider from 'components/to-be-cleaned/SqlEditor/PgsqlCompletionProvider'
-import getPgsqlSignatureHelpProvider from 'components/to-be-cleaned/SqlEditor/PgsqlSignatureHelpProvider'
-import { useStore } from 'hooks'
-import { SQLEditorLayout } from 'components/layouts'
import { NextPageWithLayout } from 'types'
-import { useTheme } from 'common'
-
-const SqlEditor: NextPageWithLayout = () => {
- const { meta } = useStore()
- const { isDarkMode } = useTheme()
- const sqlEditorStore: any = useSqlStore()
- const monaco = useMonaco()
-
- useEffect(() => {
- if (monaco) {
- monaco.editor.defineTheme('supabase', {
- base: isDarkMode ? 'vs-dark' : 'vs', // can also be hc-black
- inherit: true, // can also be false to completely replace the builtin rules
- rules: [
- { token: '', background: isDarkMode ? '1f1f1f' : 'f0f0f0' },
- { token: 'string.sql', foreground: '24b47e' },
- { token: 'comment', foreground: '666666' },
- // { token: 'predefined.sql', foreground: 'D4D4D4' },
- ],
- colors: {
- 'editor.background': isDarkMode ? '#1f1f1f' : '#f0f0f0',
- // 'editorGutter.background': '#30313f',
- // 'editorLineNumber.foreground': '#555671',
- },
- })
- }
- }, [monaco, isDarkMode])
-
- useEffect(() => {
- if (monaco) {
- // Enable pgsql format
- const formatprovider = monaco.languages.registerDocumentFormattingEditProvider('pgsql', {
- async provideDocumentFormattingEdits(model: any) {
- const value = model.getValue()
- const formatted = await formatPgsql(value)
- return [
- {
- range: model.getFullModelRange(),
- text: formatted,
- },
- ]
- },
- })
-
- // register completion item provider for pgsql
- const completeProvider = monaco.languages.registerCompletionItemProvider(
- 'pgsql',
- getPgsqlCompletionProvider(monaco, sqlEditorStore)
- )
- const signatureHelpProvider = monaco.languages.registerSignatureHelpProvider(
- 'pgsql',
- getPgsqlSignatureHelpProvider(monaco, sqlEditorStore)
- )
-
- return () => {
- formatprovider.dispose()
- completeProvider.dispose()
- signatureHelpProvider.dispose()
- }
- }
- }, [monaco])
-
- async function formatPgsql(value: any) {
- try {
- const formatted = await meta.formatQuery(value)
- if (formatted.error) throw formatted.error
- return formatted
- } catch (error) {
- console.error('formatPgsql error:', error)
- return value
- }
- }
-
- function renderTabContent() {
- const tabInfo = sqlEditorStore.activeTab
- if (!tabInfo) return null
-
- const { type } = tabInfo
- switch (type) {
- case TAB_TYPES.WELCOME:
- return <TabWelcome />
- case TAB_TYPES.SQL_QUERY:
- return (
- <div className="SQLTabContainer flex-1">
- <TabSqlQuery />
- </div>
- )
- }
- }
+import { SQLEditorLayout } from 'components/layouts'
+import { SQLTemplates } from 'components/interfaces/SQLEditor'
- return <>{renderTabContent()}</>
+const SqlEditorWelcome: NextPageWithLayout = () => {
+ return <SQLTemplates />
}
-SqlEditor.getLayout = (page) => <SQLEditorLayout title="SQL">{page}</SQLEditorLayout>
-
-export default observer(SqlEditor)
+SqlEditorWelcome.getLayout = (page) => <SQLEditorLayout title="SQL">{page}</SQLEditorLayout>
+export default observer(SqlEditorWelcome)
diff --git a/studio/state/sql-editor.ts b/studio/state/sql-editor.ts
new file mode 100644
index 00000000000..a9f3308f24c
--- /dev/null
+++ b/studio/state/sql-editor.ts
@@ -0,0 +1,138 @@
+import { Content } from 'data/content/content-query'
+import { SqlSnippet } from 'data/content/sql-snippets-query'
+import { updateContent } from 'data/content/content-update-mutation'
+import { debounce, memoize } from 'lodash'
+import { proxy, snapshot, subscribe, useSnapshot } from 'valtio'
+import { devtools, proxySet } from 'valtio/utils'
+
+export const sqlEditorState = proxy({
+ snippets: {} as {
+ [key: string]: {
+ snippet: SqlSnippet
+ splitSizes: number[]
+ utilityPanelCollapsed: boolean
+ projectRef: string
+ }
+ },
+ results: {} as {
+ [key: string]: {
+ rows: any[]
+ error?: any
+ }[]
+ },
+ loaded: {} as {
+ [key: string]: true
+ },
+ needsSaving: proxySet<string>([]),
+ savingStates: {} as {
+ [key: string]: 'IDLE' | 'UPDATING' | 'UPDATING_FAILED'
+ },
+
+ setInitialSnippets: (snippets: SqlSnippet[], projectRef: string) => {
+ snippets.forEach((snippet) => {
+ if (snippet.id && !sqlEditorState.snippets[snippet.id]) {
+ sqlEditorState.snippets[snippet.id] = {
+ snippet,
+ splitSizes: [50, 50],
+ utilityPanelCollapsed: false,
+ projectRef,
+ }
+ sqlEditorState.results[snippet.id] = []
+ sqlEditorState.savingStates[snippet.id] = 'IDLE'
+ }
+
+ sqlEditorState.loaded[projectRef] = true
+ })
+ },
+ setSplitSizes: (id: string, splitSizes: number[]) => {
+ if (sqlEditorState.snippets[id]) {
+ sqlEditorState.snippets[id].splitSizes = splitSizes
+
+ if (sqlEditorState.snippets[id].utilityPanelCollapsed) {
+ sqlEditorState.snippets[id].utilityPanelCollapsed = false
+ }
+ }
+ },
+ collapseUtilityPanel: (id: string) => {
+ if (sqlEditorState.snippets[id]) {
+ sqlEditorState.snippets[id].utilityPanelCollapsed = true
+ }
+ },
+ restoreUtilityPanel: (id: string) => {
+ if (sqlEditorState.snippets[id]) {
+ sqlEditorState.snippets[id].utilityPanelCollapsed = false
+ }
+ },
+ setSql: (id: string, sql: string) => {
+ if (sqlEditorState.snippets[id]) {
+ sqlEditorState.snippets[id].snippet.content.sql = sql
+ sqlEditorState.needsSaving.add(id)
+ }
+ },
+ addNeedsSaving: (id: string) => {
+ sqlEditorState.needsSaving.add(id)
+ },
+ addResult: (id: string, results: any[]) => {
+ if (sqlEditorState.results[id]) {
+ sqlEditorState.results[id].unshift({ rows: results })
+ }
+ },
+ addResultError: (id: string, error: any) => {
+ if (sqlEditorState.results[id]) {
+ sqlEditorState.results[id].unshift({ rows: [], error })
+ }
+ },
+ addFavorite: (id: string) => {
+ if (sqlEditorState.snippets[id]) {
+ sqlEditorState.snippets[id].snippet.content.favorite = true
+ sqlEditorState.needsSaving.add(id)
+ }
+ },
+ removeFavorite: (id: string) => {
+ if (sqlEditorState.snippets[id]) {
+ sqlEditorState.snippets[id].snippet.content.favorite = false
+ sqlEditorState.needsSaving.add(id)
+ }
+ },
+})
+
+export const getSqlEditorStateSnapshot = () => snapshot(sqlEditorState)
+
+export const useSqlEditorStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>
+ useSnapshot(sqlEditorState, options)
+
+async function update(id: string, projectRef: string, content: Partial<Content>) {
+ try {
+ await updateContent({ projectRef, id, content })
+ sqlEditorState.savingStates[id] = 'IDLE'
+ } catch (error) {
+ sqlEditorState.savingStates[id] = 'UPDATING_FAILED'
+ }
+}
+
+const memoizedUpdate = memoize((_id: string) => debounce(update, 1500))
+const debouncedUpdate = (id: string, projectRef: string, content: Partial<Content>) =>
+ memoizedUpdate(id)(id, projectRef, content)
+
+if (typeof window !== 'undefined') {
+ devtools(sqlEditorState, { name: 'sqlEditorState', enabled: true })
+
+ subscribe(sqlEditorState.needsSaving, () => {
+ const state = getSqlEditorStateSnapshot()
+
+ state.needsSaving.forEach((id) => {
+ const snippet = state.snippets[id]
+
+ if (snippet) {
+ debouncedUpdate(id, snippet.projectRef, {
+ content: { ...snippet.snippet.content, content_id: id },
+ type: 'sql',
+ id,
+ })
+
+ sqlEditorState.needsSaving.delete(id)
+ sqlEditorState.savingStates[id] = 'UPDATING'
+ }
+ })
+ })
+}