The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: Save the selected schema in the URL and local storage (#28662)
Ivan Vasilov8c6d0f189078
diff --git a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsxindex 3332d036ada..7738c14b7d3 100644--- a/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx+++ b/apps/studio/components/grid/components/formatter/ForeignKeyFormatter.tsx@@ -1,14 +1,13 @@-import * as Tooltip from '@radix-ui/react-tooltip'import { ArrowRight } from 'lucide-react'import Link from 'next/link'import type { PropsWithChildren } from 'react'import type { RenderCellProps } from 'react-data-grid'-import { Button } from 'ui'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'import { useTableQuery } from 'data/tables/table-query'import { useTablesQuery } from 'data/tables/tables-query'-import { useTableEditorStateSnapshot } from 'state/table-editor'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'+import { Button, Tooltip_Shadcn_, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_ } from 'ui'import type { SupaRow } from '../../types'import { NullValue } from '../common/NullValue'@@ -19,7 +18,7 @@ interface Props extends PropsWithChildren<RenderCellProps<SupaRow, unknown>> {export const ForeignKeyFormatter = (props: Props) => {const { project } = useProjectContext()- const snap = useTableEditorStateSnapshot()+ const { selectedSchema } = useQuerySchemaState()const { projectRef, tableId, row, column } = propsconst id = tableId ? Number(tableId) : undefined@@ -54,8 +53,8 @@ export const ForeignKeyFormatter = (props: Props) => {{value === null ? <NullValue /> : value}</span>{relationship !== undefined && targetTable !== undefined && value !== null && (- <Tooltip.Root delayDuration={0}>- <Tooltip.Trigger asChild>+ <Tooltip_Shadcn_ delayDuration={0}>+ <TooltipTrigger_Shadcn_ asChild><ButtonasChildtype="default"@@ -64,29 +63,14 @@ export const ForeignKeyFormatter = (props: Props) => {style={{ padding: '3px' }}><Link- href={`/project/${projectRef}/editor/${targetTable?.id}?filter=${relationship?.target_column_name}%3Aeq%3A${value}`}- onClick={() => snap.setSelectedSchemaName(relationship.target_table_schema)}+ href={`/project/${projectRef}/editor/${targetTable?.id}?schema=${selectedSchema}&filter=${relationship?.target_column_name}%3Aeq%3A${value}`}><ArrowRight size={14} /></Link></Button>- </Tooltip.Trigger>- <Tooltip.Portal>- <Tooltip.Portal>- <Tooltip.Content side="bottom">- <Tooltip.Arrow className="radix-tooltip-arrow" />- <div- className={[- 'rounded bg-alternative py-1 px-2 leading-none shadow',- 'border border-background',- ].join(' ')}- >- <span className="text-xs text-foreground">View referencing record</span>- </div>- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Portal>- </Tooltip.Root>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom">View referencing record</TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>)}</div>)diff --git a/apps/studio/components/interfaces/Database/EnumeratedTypes/EnumeratedTypes.tsx b/apps/studio/components/interfaces/Database/EnumeratedTypes/EnumeratedTypes.tsxindex a35e7ce1df9..cc39663d5dc 100644--- a/apps/studio/components/interfaces/Database/EnumeratedTypes/EnumeratedTypes.tsx+++ b/apps/studio/components/interfaces/Database/EnumeratedTypes/EnumeratedTypes.tsx@@ -1,13 +1,5 @@import { Edit, MoreVertical, Search, Trash } from 'lucide-react'import { useState } from 'react'-import {- Button,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- Input,-} from 'ui'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'import Table from 'components/to-be-cleaned/Table'@@ -19,7 +11,16 @@ import {EnumeratedType,useEnumeratedTypesQuery,} from 'data/enumerated-types/enumerated-types-query'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Input,+} from 'ui'import ProtectedSchemaWarning from '../ProtectedSchemaWarning'import CreateEnumeratedTypeSidePanel from './CreateEnumeratedTypeSidePanel'import DeleteEnumeratedTypeModal from './DeleteEnumeratedTypeModal'@@ -28,7 +29,7 @@ import EditEnumeratedTypeSidePanel from './EditEnumeratedTypeSidePanel'const EnumeratedTypes = () => {const { project } = useProjectContext()const [search, setSearch] = useState('')- const [selectedSchema, setSelectedSchema] = useState('public')+ const { selectedSchema, setSelectedSchema } = useQuerySchemaState()const [showCreateTypePanel, setShowCreateTypePanel] = useState(false)const [selectedTypeToEdit, setSelectedTypeToEdit] = useState<EnumeratedType>()const [selectedTypeToDelete, setSelectedTypeToDelete] = useState<EnumeratedType>()diff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsxindex 01e3e039684..2dfa7f6a0b9 100644--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx@@ -3,7 +3,6 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'import { noop, partition } from 'lodash'import { Search } from 'lucide-react'import { useRouter } from 'next/router'-import { useEffect } from 'react'import { useParams } from 'common'import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'@@ -16,6 +15,7 @@ import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import { useDatabaseFunctionsQuery } from 'data/database-functions/database-functions-query'import { useSchemasQuery } from 'data/database/schemas-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'import { Input } from 'ui'import ProtectedSchemaWarning from '../../ProtectedSchemaWarning'@@ -34,16 +34,10 @@ const FunctionsList = ({}: FunctionsListProps) => {const { project } = useProjectContext()const router = useRouter()- const { schema, search } = useParams()- const selectedSchema = schema ?? 'public'+ const { search } = useParams()+ const { selectedSchema, setSelectedSchema } = useQuerySchemaState()const filterString = search ?? ''- const setSelectedSchema = (s: string) => {- const url = new URL(document.URL)- url.searchParams.delete('search')- url.searchParams.set('schema', s)- router.push(url)- }const setFilterString = (str: string) => {const url = new URL(document.URL)if (str === '') {@@ -54,13 +48,6 @@ const FunctionsList = ({router.push(url)}- // update the url to point to public schema- useEffect(() => {- if (schema !== selectedSchema) {- setSelectedSchema(selectedSchema)- }- }, [])-const canCreateFunctions = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE,'functions'@@ -118,7 +105,12 @@ const FunctionsList = ({size="small"showError={false}selectedSchemaName={selectedSchema}- onSelectSchema={setSelectedSchema}+ onSelectSchema={(schema) => {+ const url = new URL(document.URL)+ url.searchParams.delete('search')+ router.push(url)+ setSelectedSchema(schema)+ }}/><Inputplaceholder="Search for a function"diff --git a/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx b/apps/studio/components/interfaces/Database/Indexes/Indexes.tsxindex fbbfa644c66..63e9b71dc08 100644--- a/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx+++ b/apps/studio/components/interfaces/Database/Indexes/Indexes.tsx@@ -12,6 +12,7 @@ import ShimmeringLoader, { GenericSkeletonLoader } from 'components/ui/Shimmerinimport { DatabaseIndex, useIndexesQuery } from 'data/database/indexes-query'import { useSchemasQuery } from 'data/database/schemas-query'import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'import { Button, IconAlertCircle, IconSearch, IconTrash, Input, SidePanel } from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'@@ -23,7 +24,7 @@ const Indexes = () => {const { schema: urlSchema, table } = useParams()const [search, setSearch] = useState('')- const [selectedSchema, setSelectedSchema] = useState('public')+ const { selectedSchema, setSelectedSchema } = useQuerySchemaState()const [showCreateIndex, setShowCreateIndex] = useState(false)const [selectedIndex, setSelectedIndex] = useState<DatabaseIndex>()const [selectedIndexToDelete, setSelectedIndexToDelete] = useState<DatabaseIndex>()diff --git a/apps/studio/components/interfaces/Database/Tables/TableList.tsx b/apps/studio/components/interfaces/Database/Tables/TableList.tsxindex 7225bf0f5ab..07bc8838718 100644--- a/apps/studio/components/interfaces/Database/Tables/TableList.tsx+++ b/apps/studio/components/interfaces/Database/Tables/TableList.tsx@@ -33,6 +33,7 @@ import { useMaterializedViewsQuery } from 'data/materialized-views/materialized-import { useTablesQuery } from 'data/tables/tables-query'import { useViewsQuery } from 'data/views/views-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'import { useTableEditorStateSnapshot } from 'state/table-editor'import {@@ -71,6 +72,7 @@ const TableList = ({const { ref } = useParams()const { project } = useProjectContext()const snap = useTableEditorStateSnapshot()+ const { selectedSchema, setSelectedSchema } = useQuerySchemaState()const [filterString, setFilterString] = useState<string>('')const [visibleTypes, setVisibleTypes] = useState<string[]>(Object.values(ENTITY_TYPE))@@ -86,7 +88,7 @@ const TableList = ({{projectRef: project?.ref,connectionString: project?.connectionString,- schema: snap.selectedSchemaName,+ schema: selectedSchema,sortByProperty: 'name',includeColumns: true,},@@ -109,7 +111,7 @@ const TableList = ({{projectRef: project?.ref,connectionString: project?.connectionString,- schema: snap.selectedSchemaName,+ schema: selectedSchema,},{select(views) {@@ -130,7 +132,7 @@ const TableList = ({{projectRef: project?.ref,connectionString: project?.connectionString,- schema: snap.selectedSchemaName,+ schema: selectedSchema,},{select(materializedViews) {@@ -153,7 +155,7 @@ const TableList = ({{projectRef: project?.ref,connectionString: project?.connectionString,- schema: snap.selectedSchemaName,+ schema: selectedSchema,},{select(foreignTables) {@@ -177,7 +179,7 @@ const TableList = ({const entities = formatAllEntities({ tables, views, materializedViews, foreignTables }).filter((x) => visibleTypes.includes(x.type))- const isLocked = EXCLUDED_SCHEMAS.includes(snap.selectedSchemaName || '')+ const isLocked = EXCLUDED_SCHEMAS.includes(selectedSchema)const error = tablesError || viewsError || materializedViewsError || foreignTablesErrorconst isError = isErrorTables || isErrorViews || isErrorMaterializedViews || isErrorForeignTables@@ -203,8 +205,8 @@ const TableList = ({className="w-[260px]"size="small"showError={false}- selectedSchemaName={snap.selectedSchemaName}- onSelectSchema={snap.setSelectedSchemaName}+ selectedSchemaName={selectedSchema}+ onSelectSchema={setSelectedSchema}/><Popover_Shadcn_><PopoverTrigger_Shadcn_ asChild>@@ -276,7 +278,7 @@ const TableList = ({)}</div>- {isLocked && <ProtectedSchemaWarning schema={snap.selectedSchemaName} entity="tables" />}+ {isLocked && <ProtectedSchemaWarning schema={selectedSchema} entity="tables" />}{isLoading && <GenericSkeletonLoader />}@@ -305,7 +307,7 @@ const TableList = ({body={<>{entities.length === 0 && filterString.length === 0 && (- <Table.tr key={snap.selectedSchemaName}>+ <Table.tr key={selectedSchema}><Table.td colSpan={7}>{visibleTypes.length === 0 ? (<>@@ -331,7 +333,7 @@ const TableList = ({.join(', ')}, and ${formatTooltipText(visibleTypes[visibleTypes.length - 1])}s`}{' '}- found in the schema "{snap.selectedSchemaName}"+ found in the schema "{selectedSchema}"</p></>)}@@ -339,7 +341,7 @@ const TableList = ({</Table.tr>)}{entities.length === 0 && filterString.length > 0 && (- <Table.tr key={snap.selectedSchemaName}>+ <Table.tr key={selectedSchema}><Table.td colSpan={7}><p className="text-sm text-foreground">No results found</p><p className="text-sm text-foreground-light">@@ -517,7 +519,7 @@ const TableList = ({if (canUpdateTables && !isLocked) {onDeleteTable({...x,- schema: snap.selectedSchemaName,+ schema: selectedSchema,})}}}diff --git a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsxindex 03f4591868b..99e643ab3d9 100644--- a/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx+++ b/apps/studio/components/interfaces/Database/Triggers/TriggersList/TriggersList.tsx@@ -14,6 +14,7 @@ import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import { useDatabaseTriggersQuery } from 'data/database-triggers/database-triggers-query'import { useSchemasQuery } from 'data/database/schemas-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'import ProtectedSchemaWarning from '../../ProtectedSchemaWarning'import TriggerList from './TriggerList'@@ -30,7 +31,7 @@ const TriggersList = ({deleteTrigger = noop,}: TriggersListProps) => {const { project } = useProjectContext()- const [selectedSchema, setSelectedSchema] = useState<string>('public')+ const { selectedSchema, setSelectedSchema } = useQuerySchemaState()const [filterString, setFilterString] = useState<string>('')const { data: schemas } = useSchemasQuery({diff --git a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsxindex 310554ec879..e7e4bcc2d05 100644--- a/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/DeleteConfirmationDialogs.tsx@@ -11,6 +11,7 @@ import { useTableRowDeleteMutation } from 'data/table-rows/table-row-delete-mutaimport { useTableRowTruncateMutation } from 'data/table-rows/table-row-truncate-mutation'import { useTableDeleteMutation } from 'data/tables/table-delete-mutation'import { useGetTables } from 'data/tables/tables-query'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import type { TableLike } from 'hooks/misc/useTable'import { useUrlState } from 'hooks/ui/useUrlState'import { noop } from 'lib/void'@@ -30,6 +31,7 @@ const DeleteConfirmationDialogs = ({}: DeleteConfirmationDialogsProps) => {const { project } = useProjectContext()const snap = useTableEditorStateSnapshot()+ const { selectedSchema } = useQuerySchemaState()const [{ filter }, setParams] = useUrlState({ arrayKeys: ['filter', 'sort'] })const filters = formatFilterURLParams(filter as string[])@@ -76,7 +78,7 @@ const DeleteConfirmationDialogs = ({})const { mutate: deleteTable } = useTableDeleteMutation({onSuccess: async () => {- const tables = await getTables(snap.selectedSchemaName)+ const tables = await getTables(selectedSchema)onAfterDeleteTable(tables)toast.success(`Successfully deleted table "${selectedTable?.name}"`)},diff --git a/apps/studio/components/interfaces/TableGridEditor/EmptyState.tsx b/apps/studio/components/interfaces/TableGridEditor/EmptyState.tsxindex 6112a84ae08..bd8f0a90362 100644--- a/apps/studio/components/interfaces/TableGridEditor/EmptyState.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/EmptyState.tsx@@ -5,6 +5,7 @@ import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'import { useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useLocalStorage } from 'hooks/misc/useLocalStorage'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'import { useTableEditorStateSnapshot } from 'state/table-editor'@@ -12,7 +13,8 @@ export interface EmptyStateProps {}const EmptyState = ({}: EmptyStateProps) => {const snap = useTableEditorStateSnapshot()- const isProtectedSchema = EXCLUDED_SCHEMAS.includes(snap.selectedSchemaName)+ const { selectedSchema } = useQuerySchemaState()+ const isProtectedSchema = EXCLUDED_SCHEMAS.includes(selectedSchema)const canCreateTables =useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables') && !isProtectedSchema@@ -25,7 +27,7 @@ const EmptyState = ({}: EmptyStateProps) => {const { data } = useEntityTypesQuery({projectRef: project?.ref,connectionString: project?.connectionString,- schema: snap.selectedSchemaName,+ schema: selectedSchema,sort,})diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsxindex 036b66936aa..84b7ba1686c 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.tsx@@ -21,14 +21,14 @@ import InformationBox from 'components/ui/InformationBox'import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'import { useSchemasQuery } from 'data/database/schemas-query'import { useTablesQuery } from 'data/tables/tables-query'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { uuidv4 } from 'lib/helpers'-import { useTableEditorStateSnapshot } from 'state/table-editor'import ActionBar from '../ActionBar'import { NUMERICAL_TYPES, TEXT_TYPES } from '../SidePanelEditor.constants'+import type { ColumnField } from '../SidePanelEditor.types'import { FOREIGN_KEY_CASCADE_OPTIONS } from './ForeignKeySelector.constants'import type { ForeignKey } from './ForeignKeySelector.types'import { generateCascadeActionDescription } from './ForeignKeySelector.utils'-import type { ColumnField } from '../SidePanelEditor.types'const EMPTY_STATE: ForeignKey = {id: undefined,@@ -61,7 +61,7 @@ export const ForeignKeySelector = ({onSaveRelation,}: ForeignKeySelectorProps) => {const { project } = useProjectContext()- const snap = useTableEditorStateSnapshot()+ const { selectedSchema } = useQuerySchemaState()const [fk, setFk] = useState(EMPTY_STATE)const [errors, setErrors] = useState<{ columns?: string; types?: any[]; typeNotice?: any[] }>({})@@ -302,8 +302,7 @@ export const ForeignKeySelector = ({</label><div className="grid grid-cols-10 gap-y-2"><div className="col-span-5 text-xs text-foreground-lighter">- {snap.selectedSchemaName}.- {table.name.length > 0 ? table.name : '[unnamed table]'}+ {selectedSchema}.{table.name.length > 0 ? table.name : '[unnamed table]'}</div><div className="col-span-4 text-xs text-foreground-lighter text-right">{fk.schema}.{fk.table}diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.tsxindex f016c0f7416..ce381d418ce 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/ForeignKeysManagement/ForeignKeysManagement.tsx@@ -5,14 +5,13 @@ import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectConteimport AlertError from 'components/ui/AlertError'import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import { useForeignKeyConstraintsQuery } from 'data/database/foreign-key-constraints-query'-import { useTableEditorStateSnapshot } from 'state/table-editor'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import type { ResponseError } from 'types'import { ForeignKeySelector } from '../../ForeignKeySelector/ForeignKeySelector'+import type { ForeignKey } from '../../ForeignKeySelector/ForeignKeySelector.types'import type { TableField } from '../TableEditor.types'import { ForeignKeyRow } from './ForeignKeyRow'-import type { ForeignKey } from '../../ForeignKeySelector/ForeignKeySelector.types'import { checkIfRelationChanged } from './ForeignKeysManagement.utils'-import { uuidv4 } from 'lib/helpers'interface ForeignKeysManagementProps {table: TableField@@ -30,7 +29,7 @@ export const ForeignKeysManagement = ({onUpdateFkRelations,}: ForeignKeysManagementProps) => {const { project } = useProjectContext()- const snap = useTableEditorStateSnapshot()+ const { selectedSchema } = useQuerySchemaState()const [open, setOpen] = useState(false)const [selectedFk, setSelectedFk] = useState<ForeignKey>()@@ -38,7 +37,7 @@ export const ForeignKeysManagement = ({const { data, error, isLoading, isSuccess, isError } = useForeignKeyConstraintsQuery({projectRef: project?.ref,connectionString: project?.connectionString,- schema: snap.selectedSchemaName,+ schema: selectedSchema,})const getRelationStatus = (fk: ForeignKey) => {diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsxindex 28e16eeaad8..47e3de7fc46 100644--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx@@ -18,10 +18,10 @@ import {} from 'data/database/foreign-key-constraints-query'import { useEnumeratedTypesQuery } from 'data/enumerated-types/enumerated-types-query'import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { useUrlState } from 'hooks/ui/useUrlState'import { EXCLUDED_SCHEMAS_WITHOUT_EXTENSIONS } from 'lib/constants/schemas'import { ExternalLink } from 'lucide-react'-import { useTableEditorStateSnapshot } from 'state/table-editor'import ActionBar from '../ActionBar'import type { ForeignKey } from '../ForeignKeySelector/ForeignKeySelector.types'import { formatForeignKeys } from '../ForeignKeySelector/ForeignKeySelector.utils'@@ -39,6 +39,7 @@ import {generateTableFieldFromPostgresTable,validateFields,} from './TableEditor.utils'+import { useTableEditorStateSnapshot } from 'state/table-editor'export interface TableEditorProps {table?: PostgresTable@@ -78,6 +79,7 @@ const TableEditor = ({}: TableEditorProps) => {const snap = useTableEditorStateSnapshot()const { project } = useProjectContext()+ const { selectedSchema } = useQuerySchemaState()const isNewRecord = isUndefined(table)const realtimeEnabled = useIsFeatureEnabled('realtime:all')@@ -187,7 +189,7 @@ const TableEditor = ({if (isEmpty(errors)) {const payload = {name: tableFields.name.trim(),- schema: snap.selectedSchemaName,+ schema: selectedSchema,comment: tableFields.comment?.trim(),...(!isNewRecord && { rls_enabled: tableFields.isRLSEnabled }),}@@ -247,9 +249,7 @@ const TableEditor = ({size="large"key="TableEditor"visible={visible}- header={- <HeaderTitle schema={snap.selectedSchemaName} table={table} isDuplicating={isDuplicating} />- }+ header={<HeaderTitle schema={selectedSchema} table={table} isDuplicating={isDuplicating} />}className={`transition-all duration-100 ease-in ${isImportingSpreadsheet ? ' mr-32' : ''}`}onCancel={closePanel}onConfirm={() => (resolve: () => void) => onSaveChanges(resolve)}diff --git a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsxindex 6e5a046addc..151373fd4fe 100644--- a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx+++ b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx@@ -329,13 +329,11 @@ const TableGridEditor = ({{(isViewSelected || isTableSelected) && <TableDefinition id={selectedTable?.id} />}</SupabaseGrid>- {snap.selectedSchemaName !== undefined && (- <SidePanelEditor- editable={!isReadOnly && canEditViaTableEditor}- selectedTable={selectedTable as PostgresTable}- onTableCreated={onTableCreated}- />- )}+ <SidePanelEditor+ editable={!isReadOnly && canEditViaTableEditor}+ selectedTable={selectedTable as PostgresTable}+ onTableCreated={onTableCreated}+ /></>)}diff --git a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsxindex 891aa5c975f..42dba9588a7 100644--- a/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx+++ b/apps/studio/components/layouts/TableEditorLayout/EntityListItem.tsx@@ -31,6 +31,7 @@ import type { Entity } from 'data/entity-types/entity-type-query'import { useProjectLintsQuery } from 'data/lint/lint-query'import { fetchAllTableRows } from 'data/table-rows/table-rows-query'import { getTable } from 'data/tables/table-query'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { useTableEditorStateSnapshot } from 'state/table-editor'import {cn,@@ -60,6 +61,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({}) => {const { project } = useProjectContext()const snap = useTableEditorStateSnapshot()+ const { selectedSchema } = useQuerySchemaState()const isActive = Number(id) === entity.id@@ -72,7 +74,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({'rls_disabled_in_public',['ERROR'],lints,- snap.selectedSchemaName+ selectedSchema).hasLintconst viewHasLints: boolean = getEntityLintDetails(@@ -80,7 +82,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({'security_definer_view',['ERROR', 'WARN'],lints,- snap.selectedSchemaName+ selectedSchema).hasLintconst materializedViewHasLints: boolean = getEntityLintDetails(@@ -88,7 +90,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({'materialized_view_in_api',['ERROR', 'WARN'],lints,- snap.selectedSchemaName+ selectedSchema).hasLintconst formatTooltipText = (entityType: string) => {@@ -394,7 +396,7 @@ const EntityListItem: ItemRenderer<Entity, EntityListItemProps> = ({<DropdownMenuItem key="view-policies" className="space-x-2" asChild><Linkkey="view-policies"- href={`/project/${projectRef}/auth/policies?schema=${snap.selectedSchemaName}&search=${entity.id}`}+ href={`/project/${projectRef}/auth/policies?schema=${selectedSchema}&search=${entity.id}`}><Lock size={12} /><span>View Policies</span>diff --git a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsxindex 976f113a05f..59d43114e3b 100644--- a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx+++ b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx@@ -1,7 +1,6 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { partition } from 'lodash'import { Filter, Plus } from 'lucide-react'-import { useRouter } from 'next/router'import { useEffect, useMemo, useState } from 'react'import { useParams } from 'common'@@ -13,8 +12,10 @@ import SchemaSelector from 'components/ui/SchemaSelector'import { useSchemasQuery } from 'data/database/schemas-query'import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'import { useEntityTypesQuery } from 'data/entity-types/entity-types-infinite-query'+import { useTableQuery } from 'data/tables/table-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useLocalStorage } from 'hooks/misc/useLocalStorage'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'import { useTableEditorStateSnapshot } from 'state/table-editor'import {@@ -38,12 +39,11 @@ import {} from 'ui-patterns/InnerSideMenu'import { useProjectContext } from '../ProjectLayout/ProjectContext'import EntityListItem from './EntityListItem'-import { useTableQuery } from 'data/tables/table-query'const TableEditorMenu = () => {- const router = useRouter()const { id } = useParams()const snap = useTableEditorStateSnapshot()+ const { selectedSchema, setSelectedSchema } = useQuerySchemaState()const [showModal, setShowModal] = useState(false)const [searchText, setSearchText] = useState<string>('')@@ -67,7 +67,7 @@ const TableEditorMenu = () => {{projectRef: project?.ref,connectionString: project?.connectionString,- schema: snap.selectedSchemaName,+ schema: selectedSchema,search: searchText.trim() || undefined,sort,filterTypes: visibleTypes,@@ -87,7 +87,7 @@ const TableEditorMenu = () => {connectionString: project?.connectionString,})- const schema = schemas?.find((schema) => schema.name === snap.selectedSchemaName)+ const schema = schemas?.find((schema) => schema.name === selectedSchema)const canCreateTables = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'tables')const [protectedSchemas] = partition(@@ -108,7 +108,7 @@ const TableEditorMenu = () => {useEffect(() => {if (selectedTable) {- snap.setSelectedSchemaName(selectedTable.schema)+ setSelectedSchema(selectedTable.schema)}}, [selectedTable])@@ -121,11 +121,10 @@ const TableEditorMenu = () => {<div className="flex flex-col gap-y-1.5"><SchemaSelectorclassName="mx-4"- selectedSchemaName={snap.selectedSchemaName}+ selectedSchemaName={selectedSchema}onSelectSchema={(name: string) => {setSearchText('')- snap.setSelectedSchemaName(name)- router.push(`/project/${project?.ref}/editor`)+ setSelectedSchema(name)}}onSelectCreateSchema={() => snap.onAddSchema()}/>diff --git a/apps/studio/hooks/misc/useLocalStorage.ts b/apps/studio/hooks/misc/useLocalStorage.tsindex 3039112a688..714311ac9ed 100644--- a/apps/studio/hooks/misc/useLocalStorage.ts+++ b/apps/studio/hooks/misc/useLocalStorage.ts@@ -1,7 +1,7 @@// Reference: https://usehooks.com/useLocalStorage/import { useQuery, useQueryClient } from '@tanstack/react-query'-import { Dispatch, SetStateAction, useState } from 'react'+import { Dispatch, SetStateAction, useCallback, useState } from 'react'export function useLocalStorage<T>(key: string, initialValue: T) {// State to store our value@@ -25,21 +25,24 @@ export function useLocalStorage<T>(key: string, initialValue: T) {// Return a wrapped version of useState's setter function that ...// ... persists the new value to localStorage.- const setValue = (value: T | ((val: T) => T)) => {- try {- // Allow value to be a function so we have same API as useState- const valueToStore = value instanceof Function ? value(storedValue) : value- // Save state- setStoredValue(valueToStore)- // Save to local storage- if (typeof window !== 'undefined') {- window.localStorage.setItem(key, JSON.stringify(valueToStore))+ const setValue = useCallback(+ (value: T | ((val: T) => T)) => {+ try {+ // Allow value to be a function so we have same API as useState+ const valueToStore = value instanceof Function ? value(storedValue) : value+ // Save state+ setStoredValue(valueToStore)+ // Save to local storage+ if (typeof window !== 'undefined') {+ window.localStorage.setItem(key, JSON.stringify(valueToStore))+ }+ } catch (error) {+ // A more advanced implementation would handle the error case+ console.log(error)}- } catch (error) {- // A more advanced implementation would handle the error case- console.log(error)- }- }+ },+ [key, storedValue]+ )return [storedValue, setValue] as const}diff --git a/apps/studio/hooks/misc/useSchemaQueryState.ts b/apps/studio/hooks/misc/useSchemaQueryState.tsnew file mode 100644index 00000000000..22313eedf31--- /dev/null+++ b/apps/studio/hooks/misc/useSchemaQueryState.ts@@ -0,0 +1,36 @@+import { parseAsString, useQueryState } from 'nuqs'++import { useParams } from 'common'+import { LOCAL_STORAGE_KEYS } from 'lib/constants'++/**+ * This hook wraps useQueryState because useQueryState imports app router for some reason which breaks the SSR in+ * the playwright tests. I've localized the issue to "NODE_ENV='test'" in the playwright tests.+ */+const useIsomorphicUseQueryState = (defaultSchema: string) => {+ if (typeof window === 'undefined') {+ return [defaultSchema, () => {}] as const+ } else {+ // eslint-disable-next-line react-hooks/rules-of-hooks+ return useQueryState('schema', parseAsString.withDefault(defaultSchema))+ }+}++export const useQuerySchemaState = () => {+ const { ref } = useParams()++ let defaultSchema = 'public'+ if (typeof window !== 'undefined') {+ defaultSchema =+ window.localStorage.getItem(LOCAL_STORAGE_KEYS.LAST_SELECTED_SCHEMA(ref ?? '')) || 'public'+ }++ const [schema, setSelectedSchema] = useIsomorphicUseQueryState(defaultSchema)++ // Update the schema to local storage on every change+ if (defaultSchema !== schema && typeof window !== 'undefined') {+ window.localStorage.setItem(LOCAL_STORAGE_KEYS.LAST_SELECTED_SCHEMA(ref ?? ''), schema)+ }++ return { selectedSchema: schema, setSelectedSchema }+}diff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.tsindex 6015c1427a7..bcfa5112170 100644--- a/apps/studio/lib/constants/index.ts+++ b/apps/studio/lib/constants/index.ts@@ -66,6 +66,9 @@ export const LOCAL_STORAGE_KEYS = {// Used for storing the last sign in method used by the userLAST_SIGN_IN_METHOD: 'supabase-last-sign-in-method',++ // Key to track the last selected schema. The project ref is intentionally put at the end for easier search in the browser console.+ LAST_SELECTED_SCHEMA: (ref: string) => `last-selected-schema-${ref}`,}export const OPT_IN_TAGS = {diff --git a/apps/studio/package.json b/apps/studio/package.jsonindex 66d38335de8..51a9db6e864 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -70,6 +70,7 @@"monaco-editor": "0.33.0","next": "^14.2.3","next-themes": "^0.3.0",+ "nuqs": "^1.17.8","openai": "^4.20.1","openapi-fetch": "^0.6.2","papaparse": "^5.3.1",diff --git a/apps/studio/pages/project/[ref]/database/column-privileges.tsx b/apps/studio/pages/project/[ref]/database/column-privileges.tsxindex 79be92673aa..6f5ce98d958 100644--- a/apps/studio/pages/project/[ref]/database/column-privileges.tsx+++ b/apps/studio/pages/project/[ref]/database/column-privileges.tsx@@ -24,6 +24,7 @@ import { useColumnPrivilegesQuery } from 'data/privileges/column-privileges-querimport { useTablePrivilegesQuery } from 'data/privileges/table-privileges-query'import { useTablesQuery } from 'data/tables/tables-query'import { useLocalStorage } from 'hooks/misc/useLocalStorage'+import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'import { LOCAL_STORAGE_KEYS } from 'lib/constants'import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'import { useAppStateSnapshot } from 'state/app-state'@@ -48,7 +49,7 @@ const PrivilegesPage: NextPageWithLayout = () => {const { flags } = featurePreviewContextconst isEnabled = flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]- const [selectedSchema, setSelectedSchema] = useState<string>('public')+ const { selectedSchema, setSelectedSchema } = useQuerySchemaState()const [selectedTable, setSelectedTable] = useState<string | undefined>(paramTable)const [selectedRole, setSelectedRole] = useState<string>('authenticated')diff --git a/apps/studio/state/table-editor.tsx b/apps/studio/state/table-editor.tsxindex 12a09c57014..a55245d9ba3 100644--- a/apps/studio/state/table-editor.tsx+++ b/apps/studio/state/table-editor.tsx@@ -1,7 +1,6 @@import type { PostgresColumn } from '@supabase/postgres-meta'import type { SupaRow } from 'components/grid/types'import { ForeignKey } from 'components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types'-import type { ForeignRowSelectorProps } from 'components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/ForeignRowSelector/ForeignRowSelector'import type { EditValue } from 'components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types'import { PropsWithChildren, createContext, useContext, useRef } from 'react'import type { Dictionary } from 'types'@@ -55,11 +54,6 @@ export type UIState =export const createTableEditorState = () => {const state = proxy({- selectedSchemaName: 'public',- setSelectedSchemaName: (schemaName: string) => {- state.selectedSchemaName = schemaName- },-enforceExactCount: false,setEnforceExactCount: (value: boolean) => {state.enforceExactCount = valuediff --git a/package-lock.json b/package-lock.jsonindex 6a1b74b2048..a4ed5f9edd7 100644--- a/package-lock.json+++ b/package-lock.json@@ -1659,6 +1659,7 @@"monaco-editor": "0.33.0","next": "^14.2.3","next-themes": "^0.3.0",+ "nuqs": "^1.17.8","openai": "^4.20.1","openapi-fetch": "^0.6.2","papaparse": "^5.3.1",@@ -31355,6 +31356,11 @@"version": "4.0.0","license": "ISC"},+ "node_modules/mitt": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw=="+ },"node_modules/mixin-deep": {"version": "1.3.2","license": "MIT",@@ -32308,6 +32314,17 @@"version": "1.1.1","license": "MIT"},+ "node_modules/nuqs": {+ "version": "1.17.8",+ "resolved": "https://registry.npmjs.org/nuqs/-/nuqs-1.17.8.tgz",+ "integrity": "sha512-JqsnzO+hJyjJE7ebuhpHMLA2iGY48e2xr0oJQFhj7kjUmDABL2XOup47rxF5TL/5b9jEsmU2t0lAKin1VdK1/A==",+ "dependencies": {+ "mitt": "^3.0.1"+ },+ "peerDependencies": {+ "next": ">=13.4 <14.0.2 || ^14.0.3"+ }+ },"node_modules/nwsapi": {"version": "2.2.7","devOptional": true,