The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: Context view actions for views and material views (#46383)
Ali Waseemc39bb96d7482
diff --git a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsxindex 5fc2646c469..54dd57f3450 100644--- a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx@@ -7,17 +7,19 @@ import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { useTableFilter } from '@/components/grid/hooks/useTableFilter'import type { SupaRow } from '@/components/grid/types'import { useDatabaseColumnDeleteMutation } from '@/data/database-columns/database-column-delete-mutation'-import { TableLike } from '@/data/table-editor/table-editor-types'+import { useMaterializedViewDeleteMutation } from '@/data/materialized-views/materialized-view-delete-mutation'+import { Entity } from '@/data/table-editor/table-editor-types'import { useTableRowDeleteAllMutation } from '@/data/table-rows/table-row-delete-all-mutation'import { useTableRowDeleteMutation } from '@/data/table-rows/table-row-delete-mutation'import { useTableRowTruncateMutation } from '@/data/table-rows/table-row-truncate-mutation'import { useTableDeleteMutation } from '@/data/tables/table-delete-mutation'+import { useViewDeleteMutation } from '@/data/views/view-delete-mutation'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useGetImpersonatedRoleState } from '@/state/role-impersonation-state'import { useTableEditorStateSnapshot } from '@/state/table-editor'export type DeleteConfirmationDialogsProps = {- selectedTable?: TableLike+ selectedTable?: EntityonTableDeleted?: () => void}@@ -69,6 +71,32 @@ const DeleteConfirmationDialogs = ({},})+ const { mutate: deleteView } = useViewDeleteMutation({+ onSuccess: async () => {+ toast.success(`Successfully deleted view "${selectedTable?.name}"`)+ onTableDeleted?.()+ },+ onError: (error) => {+ toast.error(`Failed to delete ${selectedTable?.name}: ${error.message}`)+ },+ onSettled: () => {+ snap.closeConfirmationDialog()+ },+ })++ const { mutate: deleteMaterializedView } = useMaterializedViewDeleteMutation({+ onSuccess: async () => {+ toast.success(`Successfully deleted materialized view "${selectedTable?.name}"`)+ onTableDeleted?.()+ },+ onError: (error) => {+ toast.error(`Failed to delete ${selectedTable?.name}: ${error.message}`)+ },+ onSettled: () => {+ snap.closeConfirmationDialog()+ },+ })+const { mutate: deleteRows, isPending: isDeletingRows } = useTableRowDeleteMutation({onSuccess: () => {if (snap.confirmationDialog?.type === 'row') {@@ -121,7 +149,10 @@ const DeleteConfirmationDialogs = ({: 0const isDeleteWithCascade =- snap.confirmationDialog?.type === 'column' || snap.confirmationDialog?.type === 'table'+ snap.confirmationDialog?.type === 'column' ||+ snap.confirmationDialog?.type === 'table' ||+ snap.confirmationDialog?.type === 'view' ||+ snap.confirmationDialog?.type === 'materialized-view'? snap.confirmationDialog.isDeleteWithCascade: false@@ -156,6 +187,34 @@ const DeleteConfirmationDialogs = ({})}+ const onConfirmDeleteView = async () => {+ if (snap.confirmationDialog?.type !== 'view') return+ if (!project || !selectedTable) return++ deleteView({+ projectRef: project.ref,+ connectionString: project.connectionString,+ id: selectedTable.id,+ name: selectedTable.name,+ schema: selectedTable.schema,+ cascade: isDeleteWithCascade,+ })+ }++ const onConfirmDeleteMaterializedView = async () => {+ if (snap.confirmationDialog?.type !== 'materialized-view') return+ if (!project || !selectedTable) return++ deleteMaterializedView({+ projectRef: project.ref,+ connectionString: project.connectionString,+ id: selectedTable.id,+ name: selectedTable.name,+ schema: selectedTable.schema,+ cascade: isDeleteWithCascade,+ })+ }+const getImpersonatedRoleState = useGetImpersonatedRoleState()const onConfirmDeleteRow = async () => {@@ -320,6 +379,26 @@ const DeleteConfirmationDialogs = ({</div></ConfirmationModal>+ <DropEntityConfirmationModal+ visible={snap.confirmationDialog?.type === 'view'}+ entityLabel="view"+ entityName={selectedTable?.name}+ isDeleteWithCascade={isDeleteWithCascade}+ onToggleCascade={() => snap.toggleConfirmationIsWithCascade(!isDeleteWithCascade)}+ onCancel={() => snap.closeConfirmationDialog()}+ onConfirm={onConfirmDeleteView}+ />++ <DropEntityConfirmationModal+ visible={snap.confirmationDialog?.type === 'materialized-view'}+ entityLabel="materialized view"+ entityName={selectedTable?.name}+ isDeleteWithCascade={isDeleteWithCascade}+ onToggleCascade={() => snap.toggleConfirmationIsWithCascade(!isDeleteWithCascade)}+ onCancel={() => snap.closeConfirmationDialog()}+ onConfirm={onConfirmDeleteMaterializedView}+ />+<ConfirmationModalvariant={'destructive'}size="small"@@ -352,3 +431,85 @@ const DeleteConfirmationDialogs = ({}export default DeleteConfirmationDialogs++type DropEntityConfirmationModalProps = {+ visible: boolean+ entityLabel: 'view' | 'materialized view'+ entityName?: string+ isDeleteWithCascade: boolean+ onToggleCascade: () => void+ onCancel: () => void+ onConfirm: () => void+}++const DropEntityConfirmationModal = ({+ visible,+ entityLabel,+ entityName,+ isDeleteWithCascade,+ onToggleCascade,+ onCancel,+ onConfirm,+}: DropEntityConfirmationModalProps) => {+ const checkboxId = `checkbox-cascade-${entityLabel.replace(/\s+/g, '-')}`+ return (+ <ConfirmationModal+ variant="destructive"+ size="small"+ visible={visible}+ title={+ <span className="wrap-break-word">{`Confirm deletion of ${entityLabel} "${entityName ?? ''}"`}</span>+ }+ confirmLabel="Delete"+ confirmLabelLoading="Deleting"+ onCancel={onCancel}+ onConfirm={onConfirm}+ >+ <div className="space-y-4">+ <p className="text-sm text-foreground-light">+ Are you sure you want to delete this {entityLabel}? This action cannot be undone.+ </p>+ <div className="items-top flex space-x-2">+ <Checkbox+ id={checkboxId}+ checked={isDeleteWithCascade}+ onCheckedChange={onToggleCascade}+ />+ <div className="grid gap-1.5 leading-none">+ <label+ htmlFor={checkboxId}+ className="text-sm text-foreground-light leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"+ >+ Drop {entityLabel} with cascade?+ </label>+ <p className="text-sm text-foreground-muted">+ Deletes the {entityLabel} and its dependent objects+ </p>+ </div>+ </div>+ {isDeleteWithCascade && (+ <Alert variant="warning">+ <AlertTitle>+ Warning: Dropping with cascade may result in unintended consequences+ </AlertTitle>+ <AlertDescription>+ All dependent objects will be removed, as will any objects that depend on them,+ recursively.+ </AlertDescription>+ <AlertDescription className="mt-4">+ <Button asChild size="tiny" type="default" icon={<ExternalLink />}>+ <Link+ href="https://www.postgresql.org/docs/current/ddl-depend.html"+ target="_blank"+ rel="noreferrer"+ >+ About dependency tracking+ </Link>+ </Button>+ </AlertDescription>+ </Alert>+ )}+ </div>+ </ConfirmationModal>+ )+}diff --git a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsxindex c116e66693b..52851b70db1 100644--- a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx@@ -193,7 +193,7 @@ export const TableGridEditor = ({</SupabaseGrid><DeleteConfirmationDialogs- selectedTable={isTableSelected ? selectedTable : undefined}+ selectedTable={selectedTable}onTableDeleted={onTableDeleted}/></TableEditorTableStateContextProvider>diff --git a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsxindex 8308876173c..0cff02de124 100644--- a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx+++ b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx@@ -29,6 +29,7 @@ import { getEntityLintDetails } from '@/components/interfaces/TableGridEditor/Taimport { EntityTypeIcon } from '@/components/ui/EntityTypeIcon'import { InlineLink } from '@/components/ui/InlineLink'import { getTableDefinition } from '@/data/database/table-definition-query'+import { getViewDefinition } from '@/data/database/view-definition-query'import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'import { Entity } from '@/data/entity-types/entity-types-infinite-query'import { useProjectLintsQuery } from '@/data/lint/lint-query'@@ -243,7 +244,7 @@ export const EntityListItem = ({onClick={(e) => e.preventDefault()}/></DropdownMenuTrigger>- <DropdownMenuContent side="bottom" align="start" className="w-44">+ <DropdownMenuContent side="bottom" align="start" className="w-52"><DropdownMenuItemkey="copy-name"className="space-x-2"@@ -252,7 +253,7 @@ export const EntityListItem = ({copyToClipboard(entity.name)}}>- <Copy size={12} />+ <Copy size={12} className="shrink-0" /><span>Copy name</span></DropdownMenuItem>@@ -279,16 +280,62 @@ export const EntityListItem = ({await copyToClipboard(formattedSchema, () => {toast.success('Table schema copied to clipboard', { id: toastId })})- } catch (err: any) {- toast.error('Failed to copy schema: ' + (err.message || err), { id: toastId })+ } catch (err: unknown) {+ if (err instanceof Error) {+ toast.error('Failed to copy schema: ' + (err.message || err), {+ id: toastId,+ })+ }}}}>- <Copy size={12} />+ <Copy size={12} className="shrink-0" /><span>Copy table schema</span></DropdownMenuItem>)}+ {(entity.type === ENTITY_TYPE.VIEW ||+ entity.type === ENTITY_TYPE.MATERIALIZED_VIEW) && (+ <DropdownMenuItem+ key="copy-view-definition"+ className="space-x-2"+ onClick={async (e) => {+ e.stopPropagation()+ const label =+ entity.type === ENTITY_TYPE.MATERIALIZED_VIEW ? 'materialized view' : 'view'+ const toastId = toast.loading(`Getting ${label} definition...`)++ const formattedDefinition = getViewDefinition({+ id: entity.id,+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ includeCreateStatement: true,+ }).then((definition) => {+ if (!definition) {+ throw new Error(`Failed to get ${label} definition`)+ }+ return formatSql(definition)+ })++ try {+ await copyToClipboard(formattedDefinition, () => {+ toast.success(+ `${label[0].toUpperCase() + label.slice(1)} definition copied to clipboard`,+ { id: toastId }+ )+ })+ } catch (err: any) {+ toast.error(`Failed to copy ${label} definition: ` + (err.message || err), {+ id: toastId,+ })+ }+ }}+ >+ <Copy size={12} className="shrink-0" />+ <span>Copy definition</span>+ </DropdownMenuItem>+ )}+{entity.type === ENTITY_TYPE.TABLE && (<><DropdownMenuSeparator />@@ -301,7 +348,7 @@ export const EntityListItem = ({snap.onEditTable()}}>- <Edit size={12} />+ <Edit size={12} className="shrink-0" /><span>Edit table</span></DropdownMenuItem><DropdownMenuItem@@ -312,7 +359,7 @@ export const EntityListItem = ({snap.onDuplicateTable()}}>- <Copy size={12} />+ <Copy size={12} className="shrink-0" /><span>Duplicate table</span></DropdownMenuItem><DropdownMenuItem key="view-policies" className="space-x-2" asChild>@@ -320,14 +367,14 @@ export const EntityListItem = ({key="view-policies"href={`/project/${projectRef}/auth/policies?schema=${encodeURIComponent(selectedSchema ?? '')}&search=${encodeURIComponent(String(entity.id))}`}>- <Lock size={12} />+ <Lock size={12} className="shrink-0" /><span>View policies</span></Link></DropdownMenuItem><DropdownMenuSub><DropdownMenuSubTrigger className="gap-x-2">- <Download size={12} />+ <Download size={12} className="shrink-0" />Export data</DropdownMenuSubTrigger><DropdownMenuSubContent>@@ -373,11 +420,107 @@ export const EntityListItem = ({snap.onDeleteTable()}}>- <Trash size={12} />+ <Trash size={12} className="shrink-0" /><span>Delete table</span></DropdownMenuItem></>)}++ {entity.type === ENTITY_TYPE.VIEW && (+ <>+ <DropdownMenuSeparator />++ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-x-2">+ <Download size={12} className="shrink-0" />+ Export data+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuItem+ key="download-view-csv"+ className="space-x-2"+ onClick={(e) => {+ e.stopPropagation()+ exportCsv()+ }}+ >+ <span>Export view as CSV</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ key="download-view-sql"+ className="gap-x-2"+ onClick={(e) => {+ e.stopPropagation()+ exportSql()+ }}+ >+ <span>Export view as SQL</span>+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ <DropdownMenuSeparator />+ <DropdownMenuItem+ key="delete-view"+ className="gap-x-2"+ onClick={(e) => {+ e.stopPropagation()+ snap.onDeleteView()+ }}+ >+ <Trash size={12} className="shrink-0" />+ <span>Delete view</span>+ </DropdownMenuItem>+ </>+ )}++ {entity.type === ENTITY_TYPE.MATERIALIZED_VIEW && (+ <>+ <DropdownMenuSeparator />++ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-x-2">+ <Download size={12} className="shrink-0" />+ Export data+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuItem+ key="download-mv-csv"+ className="space-x-2"+ onClick={(e) => {+ e.stopPropagation()+ exportCsv()+ }}+ >+ <span>Export view as CSV</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ key="download-mv-sql"+ className="gap-x-2"+ onClick={(e) => {+ e.stopPropagation()+ exportSql()+ }}+ >+ <span>Export view as SQL</span>+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>++ <DropdownMenuSeparator />+ <DropdownMenuItem+ key="delete-materialized-view"+ className="gap-x-2"+ onClick={(e) => {+ e.stopPropagation()+ snap.onDeleteMaterializedView()+ }}+ >+ <Trash size={12} className="shrink-0" />+ <span>Delete view</span>+ </DropdownMenuItem>+ </>+ )}</DropdownMenuContent></DropdownMenu>)}diff --git a/apps/studio/data/materialized-views/materialized-view-delete-mutation.ts b/apps/studio/data/materialized-views/materialized-view-delete-mutation.tsnew file mode 100644index 00000000000..ec53bc28314--- /dev/null+++ b/apps/studio/data/materialized-views/materialized-view-delete-mutation.ts@@ -0,0 +1,79 @@+import { ident, safeSql } from '@supabase/pg-meta/src/pg-format'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { materializedViewKeys } from './keys'+import { entityTypeKeys } from '@/data/entity-types/keys'+import { executeSql } from '@/data/sql/execute-sql-query'+import { tableEditorKeys } from '@/data/table-editor/keys'+import type { ResponseError, UseCustomMutationOptions } from '@/types'++export type MaterializedViewDeleteVariables = {+ projectRef: string+ connectionString?: string | null+ id: number+ name: string+ schema: string+ cascade?: boolean+}++export async function deleteMaterializedView({+ projectRef,+ connectionString,+ id,+ name,+ schema,+ cascade = false,+}: MaterializedViewDeleteVariables) {+ const sql = safeSql`DROP MATERIALIZED VIEW ${ident(schema)}.${ident(name)}${cascade ? safeSql` CASCADE` : safeSql``};`++ const { result } = await executeSql<void>({+ projectRef,+ connectionString,+ sql,+ queryKey: ['materialized-view', 'delete', id],+ })++ return result+}++type MaterializedViewDeleteData = Awaited<ReturnType<typeof deleteMaterializedView>>++export const useMaterializedViewDeleteMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<+ MaterializedViewDeleteData,+ ResponseError,+ MaterializedViewDeleteVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<MaterializedViewDeleteData, ResponseError, MaterializedViewDeleteVariables>({+ mutationFn: (vars) => deleteMaterializedView(vars),+ async onSuccess(data, variables, context) {+ const { id, projectRef, schema } = variables+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: tableEditorKeys.tableEditor(projectRef, id) }),+ queryClient.invalidateQueries({+ queryKey: materializedViewKeys.listBySchema(projectRef, schema),+ }),+ queryClient.invalidateQueries({ queryKey: entityTypeKeys.list(projectRef) }),+ ])++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to delete materialized view: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/views/view-delete-mutation.ts b/apps/studio/data/views/view-delete-mutation.tsnew file mode 100644index 00000000000..94a41687f97--- /dev/null+++ b/apps/studio/data/views/view-delete-mutation.ts@@ -0,0 +1,73 @@+import { ident, safeSql } from '@supabase/pg-meta/src/pg-format'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { viewKeys } from './keys'+import { entityTypeKeys } from '@/data/entity-types/keys'+import { executeSql } from '@/data/sql/execute-sql-query'+import { tableEditorKeys } from '@/data/table-editor/keys'+import type { ResponseError, UseCustomMutationOptions } from '@/types'++export type ViewDeleteVariables = {+ projectRef: string+ connectionString?: string | null+ id: number+ name: string+ schema: string+ cascade?: boolean+}++export async function deleteView({+ projectRef,+ connectionString,+ id,+ name,+ schema,+ cascade = false,+}: ViewDeleteVariables) {+ const sql = safeSql`DROP VIEW ${ident(schema)}.${ident(name)}${cascade ? safeSql` CASCADE` : safeSql``};`++ const { result } = await executeSql<void>({+ projectRef,+ connectionString,+ sql,+ queryKey: ['view', 'delete', id],+ })++ return result+}++type ViewDeleteData = Awaited<ReturnType<typeof deleteView>>++export const useViewDeleteMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<ViewDeleteData, ResponseError, ViewDeleteVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<ViewDeleteData, ResponseError, ViewDeleteVariables>({+ mutationFn: (vars) => deleteView(vars),+ async onSuccess(data, variables, context) {+ const { id, projectRef, schema } = variables+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: tableEditorKeys.tableEditor(projectRef, id) }),+ queryClient.invalidateQueries({ queryKey: viewKeys.listBySchema(projectRef, schema) }),+ queryClient.invalidateQueries({ queryKey: entityTypeKeys.list(projectRef) }),+ ])++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to delete view: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/state/table-editor.tsx b/apps/studio/state/table-editor.tsxindex 018059fdfc8..59f6372cf0f 100644--- a/apps/studio/state/table-editor.tsx+++ b/apps/studio/state/table-editor.tsx@@ -47,6 +47,8 @@ export type SidePanel =export type ConfirmationDialog =| { type: 'table'; isDeleteWithCascade: boolean }+ | { type: 'view'; isDeleteWithCascade: boolean }+ | { type: 'materialized-view'; isDeleteWithCascade: boolean }| { type: 'column'; column: SafePostgresColumn; isDeleteWithCascade: boolean }// [Joshen] Just FYI callback, numRows, allRowsSelected is a temp workaround so that// DeleteConfirmationDialog can trigger dispatch methods after the successful deletion of rows.@@ -135,6 +137,18 @@ export const createTableEditorState = () => {confirmationDialog: { type: 'table', isDeleteWithCascade: false },}},+ onDeleteView: () => {+ state.ui = {+ open: 'confirmation-dialog',+ confirmationDialog: { type: 'view', isDeleteWithCascade: false },+ }+ },+ onDeleteMaterializedView: () => {+ state.ui = {+ open: 'confirmation-dialog',+ confirmationDialog: { type: 'materialized-view', isDeleteWithCascade: false },+ }+ },/* Columns */onAddColumn: () => {@@ -225,7 +239,9 @@ export const createTableEditorState = () => {if (state.ui.open === 'confirmation-dialog' &&(state.ui.confirmationDialog.type === 'column' ||- state.ui.confirmationDialog.type === 'table')+ state.ui.confirmationDialog.type === 'table' ||+ state.ui.confirmationDialog.type === 'view' ||+ state.ui.confirmationDialog.type === 'materialized-view')) {state.ui.confirmationDialog.isDeleteWithCascade =overrideIsDeleteWithCascade ?? !state.ui.confirmationDialog.isDeleteWithCascadediff --git a/e2e/studio/features/table-editor-views.spec.ts b/e2e/studio/features/table-editor-views.spec.tsnew file mode 100644index 00000000000..27e420ac467--- /dev/null+++ b/e2e/studio/features/table-editor-views.spec.ts@@ -0,0 +1,293 @@+import crypto from 'node:crypto'+import { expect, Page } from '@playwright/test'++import { expectClipboardValue } from '../utils/clipboard.js'+import {+ createMaterializedView,+ createTable,+ createView,+ dropMaterializedView,+ dropTable,+ dropView,+} from '../utils/db/queries.js'+import { test } from '../utils/test.js'+import { toUrl } from '../utils/to-url.js'+import { createApiResponseWaiter, waitForApiResponse } from '../utils/wait-for-response.js'++/**+ * Opens the entity context menu in the table editor sidebar.+ * The entity must be the currently-selected one (canEdit = isActive && !isLocked).+ */+const openEntityContextMenu = async (page: Page, entityName: string) => {+ const entityButton = page.getByRole('button', { name: `View ${entityName}`, exact: true })+ await entityButton.click()+ await entityButton.hover()+ const menuButton = entityButton.locator('button[aria-haspopup="menu"]')+ await expect(menuButton).toBeVisible({ timeout: 30000 })+ await menuButton.click()+}++const goToTableEditor = async (page: Page, ref: string) => {+ const tableLoadWait = createApiResponseWaiter(+ page,+ 'pg-meta',+ ref,+ 'query?key=entity-types-public-'+ )+ await page.goto(toUrl(`/project/${ref}/editor?schema=public`))+ await tableLoadWait+}++const uniqueSuffix = () => crypto.randomBytes(4).toString('hex')++/**+ * Each test owns its own base table + view so tests can run in parallel without+ * stomping on each other's DB state. Use with `await using fixture = ...` so+ * cleanup runs whether the test passes or fails.+ */+const setupViewFixture = async (+ rows: Array<Record<string, string>> = [{ note: 'alpha' }, { note: 'beta' }]+) => {+ const suffix = uniqueSuffix()+ const baseTable = `pw_view_menu_base_${suffix}`+ const viewName = `pw_view_menu_view_${suffix}`+ await createTable(baseTable, 'note', rows)+ await createView(viewName, `SELECT id, note FROM public.${baseTable}`)+ return {+ baseTable,+ viewName,+ async [Symbol.asyncDispose]() {+ await dropView(viewName)+ await dropTable(baseTable)+ },+ }+}++const setupMaterializedViewFixture = async (+ rows: Array<Record<string, string>> = [{ note: 'alpha' }, { note: 'beta' }]+) => {+ const suffix = uniqueSuffix()+ const baseTable = `pw_mv_menu_base_${suffix}`+ const mvName = `pw_mv_menu_view_${suffix}`+ await createTable(baseTable, 'note', rows)+ await createMaterializedView(mvName, `SELECT id, note FROM public.${baseTable}`)+ return {+ baseTable,+ mvName,+ async [Symbol.asyncDispose]() {+ await dropMaterializedView(mvName)+ await dropTable(baseTable)+ },+ }+}++test.describe('table editor — view context menu', () => {+ test('copy name copies the view name to clipboard', async ({ page, ref }) => {+ await using fixture = await setupViewFixture()+ await goToTableEditor(page, ref)++ await openEntityContextMenu(page, fixture.viewName)+ await page.getByRole('menuitem', { name: 'Copy name' }).click()+ await expect(+ page.getByRole('menuitem', { name: 'Copy name' }),+ 'menu should close after Copy name click'+ ).not.toBeVisible()++ await expectClipboardValue({ page, value: fixture.viewName, exact: true })+ })++ test('copy view definition copies CREATE VIEW statement to clipboard', async ({ page, ref }) => {+ await using fixture = await setupViewFixture()+ await goToTableEditor(page, ref)++ await openEntityContextMenu(page, fixture.viewName)++ const definitionWait = waitForApiResponse(page, 'pg-meta', ref, 'query?key=view-definition-')+ await page.getByRole('menuitem', { name: 'Copy definition' }).click()+ await definitionWait++ await expect(+ page.getByText('View definition copied to clipboard'),+ 'success toast should appear after copy'+ ).toBeVisible({ timeout: 15000 })++ const clipboardText: string = await page.evaluate(() => navigator.clipboard.readText())+ expect(clipboardText.toLowerCase()).toContain(`create view`)+ expect(clipboardText.toLowerCase()).toContain(fixture.viewName.toLowerCase())+ })++ test('export view as CSV shows confirmation reason and downloads', async ({ page, ref }) => {+ await using fixture = await setupViewFixture()+ await goToTableEditor(page, ref)++ await openEntityContextMenu(page, fixture.viewName)+ const exportItem = page.getByRole('menuitem', { name: 'Export data' })+ await expect(exportItem).toBeVisible()+ await exportItem.hover()+ await expect(exportItem).toHaveAttribute('data-state', /open/)+ await page.getByRole('menuitem', { name: 'Export view as CSV' }).click()++ // Confirmation modal appears with reason text — guards the shared-component fix.+ await expect(+ page.getByText('Confirm to export data'),+ 'export confirmation dialog should appear'+ ).toBeVisible({ timeout: 15000 })+ await expect(+ page.getByText(/Exporting a view may cause consistency issues/i),+ 'confirmation reason text should be visible inside the modal'+ ).toBeVisible()++ const [download] = await Promise.all([+ page.waitForEvent('download'),+ page.getByRole('button', { name: 'Submit' }).click(),+ ])+ expect(download.suggestedFilename()).toContain('.csv')+ })++ test('export view as SQL shows confirmation and downloads', async ({ page, ref }) => {+ await using fixture = await setupViewFixture()+ await goToTableEditor(page, ref)++ await openEntityContextMenu(page, fixture.viewName)+ const exportItem = page.getByRole('menuitem', { name: 'Export data' })+ await expect(exportItem).toBeVisible()+ await exportItem.hover()+ await expect(exportItem).toHaveAttribute('data-state', /open/)+ await page.getByRole('menuitem', { name: 'Export view as SQL' }).click()++ await expect(+ page.getByText('Confirm to export data'),+ 'export confirmation dialog should appear'+ ).toBeVisible({ timeout: 15000 })++ const [download] = await Promise.all([+ page.waitForEvent('download'),+ page.getByRole('button', { name: 'Submit' }).click(),+ ])+ expect(download.suggestedFilename()).toContain('.sql')+ })++ test('delete view runs DROP VIEW and removes it from the sidebar', async ({ page, ref }) => {+ await using fixture = await setupViewFixture([{ note: 'alpha' }])+ await goToTableEditor(page, ref)++ await openEntityContextMenu(page, fixture.viewName)+ await page.getByRole('menuitem', { name: 'Delete view' }).click()++ await expect(+ page.getByRole('heading', { name: `Confirm deletion of view "${fixture.viewName}"` }),+ 'confirm dialog title should include the view name'+ ).toBeVisible({ timeout: 15000 })++ const deletePromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=view-delete-', {+ method: 'POST',+ })+ const entityTypesPromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=entity-types-')+ await page.getByRole('button', { name: 'Delete', exact: true }).click()+ await Promise.all([deletePromise, entityTypesPromise])++ await expect+ .poll(+ async () =>+ await page.getByRole('button', { name: `View ${fixture.viewName}`, exact: true }).count(),+ { message: 'view should be removed from the sidebar after delete' }+ )+ .toBe(0)+ })+})++test.describe('table editor — materialized view context menu', () => {+ test('copy name copies the materialized view name to clipboard', async ({ page, ref }) => {+ await using fixture = await setupMaterializedViewFixture()+ await goToTableEditor(page, ref)++ await openEntityContextMenu(page, fixture.mvName)+ await page.getByRole('menuitem', { name: 'Copy name' }).click()+ await expect(page.getByRole('menuitem', { name: 'Copy name' })).not.toBeVisible()++ await expectClipboardValue({ page, value: fixture.mvName, exact: true })+ })++ test('copy materialized view definition copies CREATE statement to clipboard', async ({+ page,+ ref,+ }) => {+ await using fixture = await setupMaterializedViewFixture()+ await goToTableEditor(page, ref)++ await openEntityContextMenu(page, fixture.mvName)++ const definitionWait = waitForApiResponse(page, 'pg-meta', ref, 'query?key=view-definition-')+ await page.getByRole('menuitem', { name: 'Copy definition' }).click()+ await definitionWait++ await expect(page.getByText('Materialized view definition copied to clipboard')).toBeVisible({+ timeout: 15000,+ })++ const clipboardText: string = await page.evaluate(() => navigator.clipboard.readText())+ expect(clipboardText.toLowerCase()).toContain('create materialized view')+ expect(clipboardText.toLowerCase()).toContain(fixture.mvName.toLowerCase())+ })++ test('export materialized view as CSV shows confirmation and downloads', async ({+ page,+ ref,+ }) => {+ await using fixture = await setupMaterializedViewFixture()+ await goToTableEditor(page, ref)++ await openEntityContextMenu(page, fixture.mvName)+ const exportItem = page.getByRole('menuitem', { name: 'Export data' })+ await expect(exportItem).toBeVisible()+ await exportItem.hover()+ await expect(exportItem).toHaveAttribute('data-state', /open/)+ await page.getByRole('menuitem', { name: 'Export view as CSV' }).click()++ await expect(+ page.getByText(/Exporting a materialized view may cause performance issues/i),+ 'materialized view-specific confirmation reason should appear'+ ).toBeVisible({ timeout: 15000 })++ const [download] = await Promise.all([+ page.waitForEvent('download'),+ page.getByRole('button', { name: 'Submit' }).click(),+ ])+ expect(download.suggestedFilename()).toContain('.csv')+ })++ test('delete materialized view runs DROP and removes it from the sidebar', async ({+ page,+ ref,+ }) => {+ await using fixture = await setupMaterializedViewFixture()+ await goToTableEditor(page, ref)++ await openEntityContextMenu(page, fixture.mvName)+ await page.getByRole('menuitem', { name: 'Delete view' }).click()++ await expect(+ page.getByRole('heading', {+ name: `Confirm deletion of materialized view "${fixture.mvName}"`,+ })+ ).toBeVisible({ timeout: 15000 })++ const deletePromise = waitForApiResponse(+ page,+ 'pg-meta',+ ref,+ 'query?key=materialized-view-delete-',+ { method: 'POST' }+ )+ const entityTypesPromise = waitForApiResponse(page, 'pg-meta', ref, 'query?key=entity-types-')+ await page.getByRole('button', { name: 'Delete', exact: true }).click()+ await Promise.all([deletePromise, entityTypesPromise])++ await expect+ .poll(+ async () =>+ await page.getByRole('button', { name: `View ${fixture.mvName}`, exact: true }).count()+ )+ .toBe(0)+ })+})diff --git a/e2e/studio/utils/db/index.ts b/e2e/studio/utils/db/index.tsindex c5979283622..177c8bb5111 100644--- a/e2e/studio/utils/db/index.ts+++ b/e2e/studio/utils/db/index.ts@@ -1,2 +1,10 @@export { query } from './client.js'-export { createTable, dropTable, tableExists } from './queries.js'+export {+ createMaterializedView,+ createTable,+ createView,+ dropMaterializedView,+ dropTable,+ dropView,+ tableExists,+} from './queries.js'diff --git a/e2e/studio/utils/db/queries.ts b/e2e/studio/utils/db/queries.tsindex cd6b8034fde..90fbe0fbb12 100644--- a/e2e/studio/utils/db/queries.ts+++ b/e2e/studio/utils/db/queries.ts@@ -69,3 +69,41 @@ export async function createTableWithRLS(export async function dropTable(tableName: string) {await query(`DROP TABLE IF EXISTS ${tableName} CASCADE`)}++/**+ * Create a view in the public schema. Assumes the underlying table already exists.+ *+ * @param viewName - The view name to create+ * @param selectSql - The SELECT statement that defines the view (without trailing semicolon)+ */+export async function createView(viewName: string, selectSql: string) {+ await query(`CREATE OR REPLACE VIEW public.${viewName} AS ${selectSql}`)+}++/**+ * Drop a view if it exists.+ *+ * @param viewName - The view name to drop+ */+export async function dropView(viewName: string) {+ await query(`DROP VIEW IF EXISTS public.${viewName} CASCADE`)+}++/**+ * Create a materialized view in the public schema.+ *+ * @param viewName - The materialized view name to create+ * @param selectSql - The SELECT statement that defines the view (without trailing semicolon)+ */+export async function createMaterializedView(viewName: string, selectSql: string) {+ await query(`CREATE MATERIALIZED VIEW IF NOT EXISTS public.${viewName} AS ${selectSql}`)+}++/**+ * Drop a materialized view if it exists.+ *+ * @param viewName - The materialized view name to drop+ */+export async function dropMaterializedView(viewName: string) {+ await query(`DROP MATERIALIZED VIEW IF EXISTS public.${viewName} CASCADE`)+}