Skip to content

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

chore: Delete MetaStore and RootStore (#20034)

Ivan Vasilov845167ca140f
diff --git a/apps/studio/components/grid/SupabaseGrid.utils.ts b/apps/studio/components/grid/SupabaseGrid.utils.ts
index cab71d76a52..92e7e164c48 100644
--- a/apps/studio/components/grid/SupabaseGrid.utils.ts
+++ b/apps/studio/components/grid/SupabaseGrid.utils.ts
@@ -112,7 +112,6 @@ export async function initTable(
gridColumns,
savedState,
editable: props.editable,
- onSqlQuery: props.onSqlQuery,
onError: props.onError ?? defaultErrorHandler,
},
})
diff --git a/apps/studio/components/grid/components/grid/SelectColumn.tsx b/apps/studio/components/grid/components/grid/SelectColumn.tsx
index 9148100d51a..42b7aff7b55 100644
--- a/apps/studio/components/grid/components/grid/SelectColumn.tsx
+++ b/apps/studio/components/grid/components/grid/SelectColumn.tsx
@@ -1,4 +1,3 @@
-import * as React from 'react'
import * as Tooltip from '@radix-ui/react-tooltip'
import {
CalculatedColumn,
@@ -12,6 +11,7 @@ import { Button, IconMaximize2 } from 'ui'
import { SELECT_COLUMN_KEY } from '../../constants'
import { useTrackedState } from '../../store'
import type { SupaRow } from '../../types'
+import { ChangeEvent, InputHTMLAttributes, SyntheticEvent } from 'react'
export const SelectColumn: CalculatedColumn<any, any> = {
key: SELECT_COLUMN_KEY,
@@ -85,12 +85,12 @@ export const SelectColumn: CalculatedColumn<any, any> = {
draggable: false,
}
-function stopPropagation(event: React.SyntheticEvent) {
+function stopPropagation(event: SyntheticEvent) {
event.stopPropagation()
}
type SharedInputProps = Pick<
- React.InputHTMLAttributes<HTMLInputElement>,
+ InputHTMLAttributes<HTMLInputElement>,
'disabled' | 'tabIndex' | 'onClick' | 'aria-label' | 'aria-labelledby'
>
@@ -113,11 +113,11 @@ function SelectCellFormatter({
const state = useTrackedState()
const { onEditRow } = state
- function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
+ function handleChange(e: ChangeEvent<HTMLInputElement>) {
onChange(e.target.checked, (e.nativeEvent as MouseEvent).shiftKey)
}
- function onEditClick(e: React.MouseEvent) {
+ function onEditClick(e: any) {
e.stopPropagation()
if (onEditRow && row) {
onEditRow(row)
@@ -182,7 +182,7 @@ function SelectCellHeader({
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
}: SelectCellHeaderProps) {
- function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
+ function handleChange(e: ChangeEvent<HTMLInputElement>) {
onChange(e.target.checked, (e.nativeEvent as MouseEvent).shiftKey)
}
diff --git a/apps/studio/components/grid/store/reducers/base.ts b/apps/studio/components/grid/store/reducers/base.ts
index 77877b02c62..8db6be135f4 100644
--- a/apps/studio/components/grid/store/reducers/base.ts
+++ b/apps/studio/components/grid/store/reducers/base.ts
@@ -25,7 +25,6 @@ export type INIT_ACTIONTYPE =
gridProps?: GridProps
savedState?: SavedState
editable?: boolean
- onSqlQuery: (query: string) => Promise<{ data?: any; error?: any }>
onError: (error: any) => void
}
}
diff --git a/apps/studio/components/grid/store/reducers/callback.ts b/apps/studio/components/grid/store/reducers/callback.ts
index 5fcb97e4c14..4f15290652c 100644
--- a/apps/studio/components/grid/store/reducers/callback.ts
+++ b/apps/studio/components/grid/store/reducers/callback.ts
@@ -7,7 +7,6 @@ export interface CallbackInitialState {
onEditRow: ((row: SupaRow) => void) | null
onEditColumn: ((columnName: string) => void) | null
onDeleteColumn: ((columnName: string) => void) | null
- onSqlQuery: ((query: string) => Promise<{ data?: any; error?: any }>) | null
}
export const callbackInitialState: CallbackInitialState = {
@@ -17,7 +16,6 @@ export const callbackInitialState: CallbackInitialState = {
onEditRow: null,
onEditColumn: null,
onDeleteColumn: null,
- onSqlQuery: null,
}
type CALLBACK_ACTIONTYPE = {
@@ -29,7 +27,6 @@ type CALLBACK_ACTIONTYPE = {
onEditRow: ((row: SupaRow) => void) | null
onEditColumn: ((columnName: string) => void) | null
onDeleteColumn: ((columnName: string) => void) | null
- onSqlQuery: ((query: string) => Promise<{ data?: any; error?: any }>) | null
}
}
@@ -44,7 +41,6 @@ const CallbackReducer = (state: CallbackInitialState, action: CALLBACK_ACTIONTYP
onEditRow: action.payload.onEditRow,
onEditColumn: action.payload.onEditColumn,
onDeleteColumn: action.payload.onDeleteColumn,
- onSqlQuery: action.payload.onSqlQuery,
}
}
diff --git a/apps/studio/components/grid/types/grid.ts b/apps/studio/components/grid/types/grid.ts
index 07742481bba..0eb6cab0a68 100644
--- a/apps/studio/components/grid/types/grid.ts
+++ b/apps/studio/components/grid/types/grid.ts
@@ -20,11 +20,6 @@ export interface SupabaseGridProps {
* database table id
*/
tableId?: string
- /**
- *
- * run sql query
- */
- onSqlQuery: (query: string) => Promise<{ data?: any; error?: any }>
/**
* Optional react node to display in grid header
diff --git a/apps/studio/components/interfaces/Account/TOTPFactors/DeleteFactorModal.tsx b/apps/studio/components/interfaces/Account/TOTPFactors/DeleteFactorModal.tsx
index 8fe0dcc54a6..37fb4319ee9 100644
--- a/apps/studio/components/interfaces/Account/TOTPFactors/DeleteFactorModal.tsx
+++ b/apps/studio/components/interfaces/Account/TOTPFactors/DeleteFactorModal.tsx
@@ -1,3 +1,4 @@
+import toast from 'react-hot-toast'
import {
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
@@ -6,9 +7,8 @@ import {
Modal,
} from 'ui'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { useMfaUnenrollMutation } from 'data/profile/mfa-unenroll-mutation'
-import { useStore } from 'hooks'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
interface DeleteFactorModalProps {
visible: boolean
@@ -23,10 +23,9 @@ const DeleteFactorModal = ({
lastFactorToBeDeleted,
onClose,
}: DeleteFactorModalProps) => {
- const { ui } = useStore()
const { mutate: unenroll, isLoading } = useMfaUnenrollMutation({
onSuccess: () => {
- ui.setNotification({ category: 'success', message: `Successfully deleted factor` })
+ toast.success(`Successfully deleted factor`)
onClose()
},
})
diff --git a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
index b19f715c8f9..0848cb88244 100644
--- a/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/Policies.tsx
@@ -6,6 +6,7 @@ import { useRouter } from 'next/router'
import { useCallback, useState } from 'react'
import toast from 'react-hot-toast'
import { IconHelpCircle } from 'ui'
+import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'
import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import ProtectedSchemaWarning from 'components/interfaces/Database/ProtectedSchemaWarning'
@@ -18,7 +19,6 @@ import { useDatabasePolicyDeleteMutation } from 'data/database-policies/database
import { useDatabasePolicyUpdateMutation } from 'data/database-policies/database-policy-update-mutation'
import { useTableUpdateMutation } from 'data/tables/table-update-mutation'
import { useTableEditorStateSnapshot } from 'state/table-editor'
-import ConfirmModal from 'ui-patterns/Dialogs/ConfirmDialog'
interface PoliciesProps {
tables: PostgresTable[]
@@ -37,7 +37,6 @@ const Policies = ({
const { ref } = useParams()
const { project } = useProjectContext()
const snap = useTableEditorStateSnapshot()
-
const isAiAssistantEnabled = useIsRLSAIAssistantEnabled()
const [selectedSchemaAndTable, setSelectedSchemaAndTable] = useState<any>({})
diff --git a/apps/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx b/apps/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx
index 1d63cccb332..94f8df1e0e4 100644
--- a/apps/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx
+++ b/apps/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx
@@ -7,7 +7,7 @@ import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectConte
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useDatabaseExtensionEnableMutation } from 'data/database-extensions/database-extension-enable-mutation'
import { useSchemasQuery } from 'data/database/schemas-query'
-import { useStore } from 'hooks'
+import { executeSql } from 'data/sql/execute-sql-query'
import {
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
@@ -30,7 +30,6 @@ interface EnableExtensionModalProps {
const EnableExtensionModal = ({ visible, extension, onCancel }: EnableExtensionModalProps) => {
const { project } = useProjectContext()
- const { meta } = useStore()
const [defaultSchema, setDefaultSchema] = useState()
const [fetchingSchemaInfo, setFetchingSchemaInfo] = useState(false)
@@ -62,10 +61,15 @@ const EnableExtensionModal = ({ visible, extension, onCancel }: EnableExtensionM
setFetchingSchemaInfo(true)
setDefaultSchema(undefined)
}
- const res = await meta.query(
- `select * from pg_available_extension_versions where name = '${extension.name}'`
- )
- if (!res.error && !cancel) setDefaultSchema(res[0].schema)
+ try {
+ const res = await executeSql({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ sql: `select * from pg_available_extension_versions where name = '${extension.name}'`,
+ })
+ if (!cancel) setDefaultSchema(res.result[0].schema)
+ } catch (error) {}
+
setFetchingSchemaInfo(false)
}
checkExtensionSchema()
diff --git a/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx b/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx
index 1a4722645b0..cab4eb7602c 100644
--- a/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx
+++ b/apps/studio/components/interfaces/Database/Triggers/CreateTrigger.tsx
@@ -4,10 +4,21 @@ import { observer, useLocalObservable } from 'mobx-react-lite'
import { createContext, useContext, useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import SVG from 'react-inlinesvg'
+import {
+ Badge,
+ Button,
+ Checkbox,
+ IconPauseCircle,
+ IconPlayCircle,
+ IconTerminal,
+ Input,
+ Listbox,
+ Modal,
+ SidePanel,
+} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import type { Dictionary } from 'types'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import FormEmptyBox from 'components/ui/FormBoxEmpty'
import NoTableState from 'components/ui/States/NoTableState'
import {
@@ -17,21 +28,9 @@ import {
import { useDatabaseTriggerCreateMutation } from 'data/database-triggers/database-trigger-create-mutation'
import { useDatabaseTriggerUpdateMutation } from 'data/database-triggers/database-trigger-update-mutation'
import { useTablesQuery } from 'data/tables/tables-query'
-import { useStore } from 'hooks'
import { BASE_PATH } from 'lib/constants'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
-import {
- Badge,
- Button,
- Checkbox,
- IconPauseCircle,
- IconPlayCircle,
- IconTerminal,
- Input,
- Listbox,
- Modal,
- SidePanel,
-} from 'ui'
+import type { Dictionary } from 'types'
import ChooseFunctionForm from './ChooseFunctionForm'
class CreateTriggerFormState {
@@ -237,7 +236,6 @@ interface CreateTriggerProps {
const CreateTrigger = ({ trigger, visible, setVisible }: CreateTriggerProps) => {
const { project } = useProjectContext()
- const { ui, meta } = useStore()
const [isClosingPanel, setIsClosingPanel] = useState(false)
const _localState = useLocalObservable(() => new CreateTriggerStore())
diff --git a/apps/studio/components/interfaces/Docs/Description.tsx b/apps/studio/components/interfaces/Docs/Description.tsx
index e308488d9b4..8cabc869455 100644
--- a/apps/studio/components/interfaces/Docs/Description.tsx
+++ b/apps/studio/components/interfaces/Docs/Description.tsx
@@ -3,7 +3,9 @@ import { noop } from 'lodash'
import { useState } from 'react'
import { Button, IconLoader } from 'ui'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import AutoTextArea from 'components/to-be-cleaned/forms/AutoTextArea'
+import { executeSql } from 'data/sql/execute-sql-query'
import { useCheckPermissions, useStore } from 'hooks'
import { timeout } from 'lib/helpers'
@@ -28,11 +30,12 @@ interface DescrptionProps {
}
const Description = ({ content, metadata, onChange = noop }: DescrptionProps) => {
- const { meta, ui } = useStore()
+ const { ui } = useStore()
const contentText = temp_removePostgrestText(content || '').trim()
const [value, setValue] = useState(contentText)
const [isUpdating, setIsUpdating] = useState(false)
+ const { project } = useProjectContext()
const { table, column, rpc } = metadata
@@ -53,22 +56,26 @@ const Description = ({ content, metadata, onChange = noop }: DescrptionProps) =>
if (rpc) query = `comment on function "${rpc}" is '${description}';`
if (query) {
- const res = await meta.query(query)
+ try {
+ await executeSql({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ sql: query,
+ })
- // [Joshen] Temp fix, immediately refreshing the docs fetches stale state
- await timeout(500)
+ // [Joshen] Temp fix, immediately refreshing the docs fetches stale state
+ await timeout(500)
- if (res.error) {
- ui.setNotification({
- error: res.error,
- category: 'error',
- message: `Failed to update description: ${res.error.message}`,
- })
- } else {
ui.setNotification({
category: 'success',
message: `Successfully updated description`,
})
+ } catch (error: any) {
+ ui.setNotification({
+ error: error,
+ category: 'error',
+ message: `Failed to update description: ${error.message}`,
+ })
}
}
diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx
index aa74d940fba..4d50fe665ee 100644
--- a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword.tsx
@@ -6,19 +6,20 @@ import { debounce } from 'lodash'
import { useEffect, useRef, useState } from 'react'
import { Button, Input, Modal } from 'ui'
-import { useIsProjectActive } from 'components/layouts/ProjectLayout/ProjectContext'
+import {
+ useIsProjectActive,
+ useProjectContext,
+} from 'components/layouts/ProjectLayout/ProjectContext'
import Panel from 'components/ui/Panel'
import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'
import { useDatabasePasswordResetMutation } from 'data/database/database-password-reset-mutation'
-import { getProjectDetail } from 'data/projects/project-detail-query'
import { useCheckPermissions, useStore } from 'hooks'
import { DEFAULT_MINIMUM_PASSWORD_STRENGTH } from 'lib/constants'
import { passwordStrength } from 'lib/helpers'
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
const ResetDbPassword = ({ disabled = false }) => {
const { ref } = useParams()
- const { ui, meta } = useStore()
+ const { ui } = useStore()
const isProjectActive = useIsProjectActive()
const { project } = useProjectContext()
@@ -38,9 +39,6 @@ const ResetDbPassword = ({ disabled = false }) => {
const { mutate: resetDatabasePassword, isLoading: isUpdatingPassword } =
useDatabasePasswordResetMutation({
onSuccess: async () => {
- const project = await getProjectDetail({ ref })
- if (project) meta.setProjectDetails(project)
-
ui.setNotification({
category: 'success',
message: 'Successfully updated database password',
diff --git a/apps/studio/components/interfaces/Settings/Vault/VaultToggle.tsx b/apps/studio/components/interfaces/Settings/Vault/VaultToggle.tsx
index 909cec0a957..35f89b0008b 100644
--- a/apps/studio/components/interfaces/Settings/Vault/VaultToggle.tsx
+++ b/apps/studio/components/interfaces/Settings/Vault/VaultToggle.tsx
@@ -11,12 +11,13 @@ import { Button, IconExternalLink } from 'ui'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useDatabaseExtensionEnableMutation } from 'data/database-extensions/database-extension-enable-mutation'
import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import { executeSql } from 'data/sql/execute-sql-query'
import { useCheckPermissions, useStore } from 'hooks'
import { BASE_PATH } from 'lib/constants'
const VaultToggle = () => {
const { ref } = useParams()
- const { meta, ui } = useStore()
+ const { ui } = useStore()
const { resolvedTheme } = useTheme()
const { project } = useProjectContext()
const [isEnabling, setIsEnabling] = useState(false)
@@ -45,10 +46,13 @@ const VaultToggle = () => {
setIsEnabling(true)
- const { error: createSchemaError } = await meta.query(
- `create schema if not exists ${vaultExtension.schema ?? 'vault'};`
- )
- if (createSchemaError) {
+ try {
+ await executeSql({
+ projectRef: project.ref,
+ connectionString: project.connectionString,
+ sql: `create schema if not exists ${vaultExtension.schema ?? 'vault'};`,
+ })
+ } catch (createSchemaError: any) {
setIsEnabling(false)
return ui.setNotification({
error: createSchemaError,
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
index 5795e48f70f..49ea8ba7f10 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.utils.tsx
@@ -5,10 +5,12 @@ import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { Query } from 'components/grid/query/Query'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import SparkBar from 'components/ui/SparkBar'
import { createDatabaseColumn } from 'data/database-columns/database-column-create-mutation'
import { deleteDatabaseColumn } from 'data/database-columns/database-column-delete-mutation'
import { updateDatabaseColumn } from 'data/database-columns/database-column-update-mutation'
+import type { Constraint } from 'data/database/constraints-query'
import { FOREIGN_KEY_CASCADE_ACTION } from 'data/database/database-query-constants'
import { ForeignKeyConstraint } from 'data/database/foreign-key-constraints-query'
import { entityTypeKeys } from 'data/entity-types/keys'
@@ -22,9 +24,7 @@ import { getTable } from 'data/tables/table-query'
import { updateTable as updateTableMutation } from 'data/tables/table-update-mutation'
import { getTables } from 'data/tables/tables-query'
import { getViews } from 'data/views/views-query'
-import { useStore } from 'hooks'
import { timeout, tryParseJson } from 'lib/helpers'
-import type { IMetaStore } from 'stores/pgmeta/MetaStore'
import {
generateCreateColumnPayload,
generateUpdateColumnPayload,
@@ -33,7 +33,6 @@ import type { ForeignKey } from './ForeignKeySelector/ForeignKeySelector.types'
import type { ColumnField, CreateColumnPayload, UpdateColumnPayload } from './SidePanelEditor.types'
import { checkIfRelationChanged } from './TableEditor/ForeignKeysManagement/ForeignKeysManagement.utils'
import type { ImportContent } from './TableEditor/TableEditor.types'
-import type { Constraint } from 'data/database/constraints-query'
const BATCH_SIZE = 1000
const CHUNK_SIZE = 1024 * 1024 * 0.1 // 0.1MB
@@ -42,31 +41,33 @@ export interface UseEncryptedColumnsArgs {
schemaName?: string
tableName?: string
}
-
-const listEncryptedColumns = async (meta: IMetaStore, schema: string, table: string) => {
+const listEncryptedColumns = async (
+ projectRef: string,
+ connectionString: string | undefined = undefined,
+ schema: string,
+ table: string
+) => {
if (!table) return []
- const views = await getViews({
- projectRef: meta.projectRef,
- connectionString: meta.connectionString,
- schema,
- })
+ const views = await getViews({ projectRef, connectionString, schema })
const decryptedView = views.find((view) => view.name === `decrypted_${table}`)
if (!decryptedView) return []
- const encryptedColumns = await meta.query(
- `SELECT column_name as name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'decrypted_${table}' and column_name like 'decrypted_%'`
- )
- if (!encryptedColumns.error) {
- return encryptedColumns.map((column: any) => column.name.split('decrypted_')[1])
- } else {
- console.error('Error fetching encrypted columns', encryptedColumns.error)
+ try {
+ const encryptedColumns = await executeSql({
+ projectRef,
+ connectionString,
+ sql: `SELECT column_name as name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'decrypted_${table}' and column_name like 'decrypted_%'`,
+ })
+ return encryptedColumns.result.map((column: any) => column.name.split('decrypted_')[1])
+ } catch (error) {
+ console.error('Error fetching encrypted columns', error)
return []
}
}
export function useEncryptedColumns({ schemaName, tableName }: UseEncryptedColumnsArgs) {
- const { meta } = useStore()
+ const { project } = useProjectContext()
const [encryptedColumns, setEncryptedColumns] = useState<string[]>([])
useEffect(() => {
@@ -74,7 +75,12 @@ export function useEncryptedColumns({ schemaName, tableName }: UseEncryptedColum
const getEncryptedColumns = async () => {
if (schemaName !== undefined && tableName !== undefined) {
- const columns = await listEncryptedColumns(meta, schemaName, tableName)
+ const columns = await listEncryptedColumns(
+ project?.ref!,
+ project?.connectionString,
+ schemaName,
+ tableName
+ )
if (isMounted) {
setEncryptedColumns(columns)
diff --git a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
index 85cd6b28494..a826bb34101 100644
--- a/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/TableGridEditor.tsx
@@ -16,6 +16,7 @@ import {
useForeignKeyConstraintsQuery,
} from 'data/database/foreign-key-constraints-query'
import { ENTITY_TYPE } from 'data/entity-types/entity-type-constants'
+import { executeSql } from 'data/sql/execute-sql-query'
import { sqlKeys } from 'data/sql/keys'
import { useTableRowUpdateMutation } from 'data/table-rows/table-row-update-mutation'
import { useCheckPermissions, useLatest, useStore, useUrlState } from 'hooks'
@@ -46,7 +47,7 @@ const TableGridEditor = ({
selectedTable,
}: TableGridEditorProps) => {
const router = useRouter()
- const { meta, ui } = useStore()
+ const { ui } = useStore()
const { ref: projectRef, id } = useParams()
const { project } = useProjectContext()
@@ -187,15 +188,6 @@ const TableGridEditor = ({
router.push(`/project/${projectRef}/editor/${table.id}`)
}
- const onSqlQuery = async (query: string) => {
- const res = await meta.query(query)
- if (res.error) {
- return { error: res.error }
- } else {
- return { data: res }
- }
- }
-
// columns must be accessed via columnsRef.current as these two functions immediately become
// stale as they are accessed via some react-tracked madness
// [TODO]: refactor out all of react-tracked
@@ -299,7 +291,6 @@ const TableGridEditor = ({
onEditRow={snap.onEditRow}
onImportData={snap.onImportData}
onError={onError}
- onSqlQuery={onSqlQuery}
onExpandJSONEditor={(column, row) => {
snap.onExpandJSONEditor({ column, row, jsonString: JSON.stringify(row[column]) || '' })
}}
diff --git a/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx b/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx
index e91aa97e4f2..67dc31d1560 100644
--- a/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx
@@ -4,15 +4,13 @@ import Link from 'next/link'
import { useEffect, useRef, useState } from 'react'
import { Button, IconAlertCircle, IconCheckCircle, IconLoader } from 'ui'
-import { getProjectDetail, invalidateProjectDetailsQuery } from 'data/projects/project-detail-query'
-import { useStore } from 'hooks'
+import { invalidateProjectDetailsQuery } from 'data/projects/project-detail-query'
import { getWithTimeout } from 'lib/common/fetch'
import { API_URL, PROJECT_STATUS } from 'lib/constants'
import { useProjectContext } from './ProjectContext'
const RestoringState = () => {
const { ref } = useParams()
- const { meta } = useStore()
const queryClient = useQueryClient()
const { project } = useProjectContext()
const checkServerInterval = useRef<number>()
@@ -48,8 +46,6 @@ const RestoringState = () => {
if (!project) return console.error('Project is required')
setLoading(true)
- const projectDetail = await getProjectDetail({ ref: project?.ref })
- if (projectDetail) meta.setProjectDetails(projectDetail)
if (ref) await invalidateProjectDetailsQuery(queryClient, ref)
}
diff --git a/apps/studio/components/layouts/ProjectLayout/UpgradingState/UpgradingState.tsx b/apps/studio/components/layouts/ProjectLayout/UpgradingState/UpgradingState.tsx
index 989c9927934..f9bef79540d 100644
--- a/apps/studio/components/layouts/ProjectLayout/UpgradingState/UpgradingState.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/UpgradingState/UpgradingState.tsx
@@ -18,15 +18,13 @@ import {
import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common/hooks'
import { useProjectUpgradingStatusQuery } from 'data/config/project-upgrade-status-query'
-import { getProjectDetail, invalidateProjectDetailsQuery } from 'data/projects/project-detail-query'
-import { useStore } from 'hooks'
+import { invalidateProjectDetailsQuery } from 'data/projects/project-detail-query'
import { IS_PLATFORM } from 'lib/constants'
import { useProjectContext } from '../ProjectContext'
import { DATABASE_UPGRADE_MESSAGES } from './UpgradingState.constants'
const UpgradingState = () => {
const { ref } = useParams()
- const { meta } = useStore()
const queryClient = useQueryClient()
const { project } = useProjectContext()
const [loading, setLoading] = useState(false)
@@ -57,8 +55,6 @@ const UpgradingState = () => {
const refetchProjectDetails = async () => {
setLoading(true)
- const projectDetail = await getProjectDetail({ ref })
- if (projectDetail) meta.setProjectDetails(projectDetail)
if (ref) await invalidateProjectDetailsQuery(queryClient, ref)
}
diff --git a/apps/studio/components/layouts/RealtimeLayout/RealtimeLayout.tsx b/apps/studio/components/layouts/RealtimeLayout/RealtimeLayout.tsx
index 1c2a87c485d..db0102aef20 100644
--- a/apps/studio/components/layouts/RealtimeLayout/RealtimeLayout.tsx
+++ b/apps/studio/components/layouts/RealtimeLayout/RealtimeLayout.tsx
@@ -2,7 +2,7 @@ import { useRouter } from 'next/router'
import { PropsWithChildren } from 'react'
import { ProductMenu } from 'components/ui/ProductMenu'
-import { useSelectedProject, useStore, withAuth } from 'hooks'
+import { useSelectedProject, withAuth } from 'hooks'
import { ProjectLayout } from '../'
import { generateRealtimeMenu } from './RealtimeMenu.utils'
@@ -11,7 +11,6 @@ export interface RealtimeLayoutProps {
}
const RealtimeLayout = ({ children }: PropsWithChildren<RealtimeLayoutProps>) => {
- const { meta } = useStore()
const project = useSelectedProject()
const router = useRouter()
diff --git a/apps/studio/components/ui/SqlEditor.tsx b/apps/studio/components/ui/SqlEditor.tsx
index a364427818d..15ab2f73845 100644
--- a/apps/studio/components/ui/SqlEditor.tsx
+++ b/apps/studio/components/ui/SqlEditor.tsx
@@ -2,7 +2,8 @@ import Editor, { OnChange, useMonaco } from '@monaco-editor/react'
import { noop } from 'lodash'
import { useEffect, useRef } from 'react'
-import { useStore } from 'hooks'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { formatQuery } from 'data/sql/format-sql-query'
// [Joshen] We should deprecate this and use CodeEditor instead
@@ -24,7 +25,7 @@ const SqlEditor = ({
onInputChange = noop,
}: SqlEditorProps) => {
const monaco = useMonaco()
- const { meta } = useStore()
+ const { project } = useProjectContext()
const editorRef = useRef<any>()
useEffect(() => {
@@ -64,8 +65,11 @@ const SqlEditor = ({
async function formatPgsql(value: any) {
try {
- const formatted = await meta.formatQuery(value)
- if (formatted.error) throw formatted.error
+ const formatted = await formatQuery({
+ projectRef: project?.ref!,
+ connectionString: project?.connectionString,
+ sql: value,
+ })
return formatted
} catch (error) {
console.error('formatPgsql error:', error)
diff --git a/apps/studio/hooks/misc/useStore.tsx b/apps/studio/hooks/misc/useStore.tsx
index 0f5b229a303..93d8629ce4a 100644
--- a/apps/studio/hooks/misc/useStore.tsx
+++ b/apps/studio/hooks/misc/useStore.tsx
@@ -3,33 +3,28 @@ import { createContext, PropsWithChildren, useContext, useEffect } from 'react'
import toast from 'react-hot-toast'
import SparkBar from 'components/ui/SparkBar'
-import type { IRootStore } from 'stores'
-import { useSelectedProject } from './useSelectedProject'
+import { IUiStore } from 'stores/UiStore'
-const StoreContext = createContext<IRootStore>(undefined!)
+const StoreContext = createContext<{ ui: IUiStore }>(undefined!)
+/**
+ * @deprecated use the toast.success/loading/error functions, imported from 'react-hot-toast'
+ */
export function useStore() {
const context = useContext(StoreContext)
if (context === undefined) {
throw new Error('useStore must be used within StoreProvider')
}
+ // returning in this way so that it's backwards compatible.
return context
}
interface StoreProvider {
- rootStore: IRootStore
+ rootStore: { ui: IUiStore }
}
export const StoreProvider = ({ children, rootStore }: PropsWithChildren<StoreProvider>) => {
const { ui } = rootStore
-
- const selectedProject = useSelectedProject()
- useEffect(() => {
- if (selectedProject) {
- rootStore.setProject(selectedProject)
- }
- }, [selectedProject])
-
useEffect(() => {
autorun(() => {
if (ui.notification) {
diff --git a/apps/studio/pages/_app.tsx b/apps/studio/pages/_app.tsx
index f764837b677..bb4e9eef9fb 100644
--- a/apps/studio/pages/_app.tsx
+++ b/apps/studio/pages/_app.tsx
@@ -31,8 +31,8 @@ import utc from 'dayjs/plugin/utc'
import Head from 'next/head'
import { useEffect, useMemo, useRef, useState } from 'react'
import toast from 'react-hot-toast'
+import { PortalToast, Toaster } from 'ui'
import { ConsentToast } from 'ui-patterns/ConsentToast'
-import PortalToast from 'ui/src/layout/PortalToast'
import Favicons from 'components/head/Favicons'
import {
@@ -41,21 +41,19 @@ import {
RouteValidationWrapper,
} from 'components/interfaces/App'
import { AppBannerContextProvider } from 'components/interfaces/App/AppBannerWrapperContext'
+import { FeaturePreviewContextProvider } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
+import FeaturePreviewModal from 'components/interfaces/App/FeaturePreview/FeaturePreviewModal'
import FlagProvider from 'components/ui/Flag/FlagProvider'
import PageTelemetry from 'components/ui/PageTelemetry'
import { useRootQueryClient } from 'data/query-client'
import { StoreProvider } from 'hooks'
import { AuthProvider } from 'lib/auth'
import { BASE_PATH, IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
-
-import { FeaturePreviewContextProvider } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
-import FeaturePreviewModal from 'components/interfaces/App/FeaturePreview/FeaturePreviewModal'
import { ProfileProvider } from 'lib/profile'
import { useAppStateSnapshot } from 'state/app-state'
-import { RootStore } from 'stores'
+import UiStore from 'stores/UiStore'
import HCaptchaLoadedStore from 'stores/hcaptcha-loaded-store'
-import type { AppPropsWithLayout } from 'types'
-import { Toaster } from 'ui'
+import { AppPropsWithLayout } from 'types'
dayjs.extend(customParseFormat)
dayjs.extend(utc)
@@ -85,7 +83,7 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
const queryClient = useRootQueryClient()
const consentToastId = useRef<string>()
- const [rootStore] = useState(() => new RootStore())
+ const [rootStore] = useState(() => ({ ui: new UiStore() }))
// [Joshen] Some issues with using createBrowserSupabaseClient
const [supabase] = useState(() =>
diff --git a/apps/studio/pages/authorize.tsx b/apps/studio/pages/authorize.tsx
index b9181d5afeb..95b98c602cf 100644
--- a/apps/studio/pages/authorize.tsx
+++ b/apps/studio/pages/authorize.tsx
@@ -1,8 +1,10 @@
+import { useParams } from 'common'
import dayjs from 'dayjs'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
+import toast from 'react-hot-toast'
+import { Alert, Button, Listbox } from 'ui'
-import { useParams } from 'common'
import AuthorizeRequesterDetails from 'components/interfaces/Organization/OAuthApps/AuthorizeRequesterDetails'
import APIAuthorizationLayout from 'components/layouts/APIAuthorizationLayout'
import { FormPanel } from 'components/ui/Forms'
@@ -11,15 +13,13 @@ import { useApiAuthorizationApproveMutation } from 'data/api-authorization/api-a
import { useApiAuthorizationDeclineMutation } from 'data/api-authorization/api-authorization-decline-mutation'
import { useApiAuthorizationQuery } from 'data/api-authorization/api-authorization-query'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
-import { useStore, withAuth } from 'hooks'
+import { withAuth } from 'hooks'
import type { NextPageWithLayout } from 'types'
-import { Alert, Button, Listbox } from 'ui'
// Need to handle if no organizations in account
// Need to handle if not logged in yet state
const APIAuthorizationPage: NextPageWithLayout = () => {
- const { ui } = useStore()
const router = useRouter()
const { auth_id } = useParams()
const [selectedOrg, setSelectedOrg] = useState<string>()
@@ -36,7 +36,7 @@ const APIAuthorizationPage: NextPageWithLayout = () => {
})
const { mutate: declineRequest, isLoading: isDeclining } = useApiAuthorizationDeclineMutation({
onSuccess: () => {
- ui.setNotification({ category: 'success', message: 'Declined API authorization request' })
+ toast.success('Declined API authorization request')
router.push('/projects')
},
})
@@ -50,28 +50,19 @@ const APIAuthorizationPage: NextPageWithLayout = () => {
const onApproveRequest = async () => {
if (!auth_id) {
- return ui.setNotification({
- category: 'error',
- message: 'Unable to approve request: auth_id is missing ',
- })
+ return toast.error('Unable to approve request: auth_id is missing ')
}
if (!selectedOrg) {
- return ui.setNotification({
- category: 'error',
- message: 'Unable to approve request: No organization selected',
- })
+ return toast.error('Unable to approve request: No organization selected')
}
approveRequest({ id: auth_id, organization_id: selectedOrg })
}
const onDeclineRequest = async () => {
- if (!auth_id)
- return ui.setNotification({
- category: 'error',
- message: 'Unable to decline request: auth_id is missing ',
- })
-
+ if (!auth_id) {
+ return toast.error('Unable to decline request: auth_id is missing ')
+ }
declineRequest({ id: auth_id })
}
diff --git a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
index 0b5e5ebd7cf..bc19bf6d3ca 100644
--- a/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
+++ b/apps/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
@@ -1,9 +1,11 @@
+import { useParams } from 'common'
import generator from 'generate-password-browser'
import { debounce } from 'lodash'
import { useRouter } from 'next/router'
import { ChangeEvent, useRef, useState } from 'react'
+import toast from 'react-hot-toast'
+import { Alert, Button, Checkbox, Input, Listbox } from 'ui'
-import { useParams } from 'common'
import { Markdown } from 'components/interfaces/Markdown'
import VercelIntegrationWindowLayout from 'components/layouts/IntegrationsLayout/VercelIntegrationWindowLayout'
import { ScaffoldColumn, ScaffoldContainer } from 'components/layouts/Scaffold'
@@ -15,13 +17,12 @@ import { useIntegrationVercelConnectionsCreateMutation } from 'data/integrations
import { useVercelProjectsQuery } from 'data/integrations/integrations-vercel-projects-query'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
import { useProjectCreateMutation } from 'data/projects/project-create-mutation'
-import { useSelectedOrganization, useStore } from 'hooks'
+import { useSelectedOrganization } from 'hooks'
import { AWS_REGIONS, DEFAULT_MINIMUM_PASSWORD_STRENGTH, PROVIDERS } from 'lib/constants'
import { passwordStrength } from 'lib/helpers'
import { getInitialMigrationSQLFromGitHubRepo } from 'lib/integration-utils'
import { useIntegrationInstallationSnapshot } from 'state/integration-installation'
import type { NextPageWithLayout } from 'types'
-import { Alert, Button, Checkbox, Input, Listbox } from 'ui'
const VercelIntegration: NextPageWithLayout = () => {
return (
@@ -53,11 +54,9 @@ VercelIntegration.getLayout = (page) => (
const CreateProject = () => {
const router = useRouter()
- const { ui } = useStore()
const selectedOrganization = useSelectedOrganization()
const [projectName, setProjectName] = useState('')
const [dbPass, setDbPass] = useState('')
- const [instanceSize, setInstanceSize] = useState('micro')
const [passwordStrengthMessage, setPasswordStrengthMessage] = useState('')
const [passwordStrengthScore, setPasswordStrengthScore] = useState(-1)
const [shouldRunMigrations, setShouldRunMigrations] = useState(true)
@@ -145,7 +144,7 @@ const CreateProject = () => {
setNewProjectRef(res.ref)
},
onError: (error) => {
- ui.setNotification({ error, category: 'error', message: error.message })
+ toast.error(error.message)
snapshot.setLoading(false)
},
})
@@ -162,18 +161,9 @@ const CreateProject = () => {
let dbSql: string | undefined
if (shouldRunMigrations) {
- const id = ui.setNotification({
- category: 'info',
- message: `Fetching initial migrations from GitHub repo`,
- })
-
+ const id = toast(`Fetching initial migrations from GitHub repo`)
dbSql = (await getInitialMigrationSQLFromGitHubRepo(externalId)) ?? undefined
-
- ui.setNotification({
- id,
- category: 'success',
- message: `Done fetching initial migrations`,
- })
+ toast.success(`Done fetching initial migrations`, { id })
}
createProject({
diff --git a/apps/studio/pages/integrations/vercel/install.tsx b/apps/studio/pages/integrations/vercel/install.tsx
index 1318c60ec4d..ece4758e980 100644
--- a/apps/studio/pages/integrations/vercel/install.tsx
+++ b/apps/studio/pages/integrations/vercel/install.tsx
@@ -1,8 +1,17 @@
+import { useParams } from 'common'
+import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useMemo, useState } from 'react'
import { toast } from 'react-hot-toast'
+import {
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ Button,
+ IconAlertTriangle,
+ IconInfo,
+} from 'ui'
-import { useParams } from 'common'
import OrganizationPicker from 'components/interfaces/Integrations/OrganizationPicker'
import { Markdown } from 'components/interfaces/Markdown'
import { getHasInstalledObject } from 'components/layouts/IntegrationsLayout/Integrations.utils'
@@ -11,18 +20,8 @@ import { ScaffoldColumn, ScaffoldContainer } from 'components/layouts/Scaffold'
import { useIntegrationsQuery } from 'data/integrations/integrations-query'
import { useVercelIntegrationCreateMutation } from 'data/integrations/vercel-integration-create-mutation'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
-import { useStore } from 'hooks'
-import Link from 'next/link'
-import type { NextPageWithLayout, Organization } from 'types'
-import {
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Alert_Shadcn_,
- Button,
- IconAlertTriangle,
- IconInfo,
-} from 'ui'
import { useIntegrationInstallationSnapshot } from 'state/integration-installation'
+import type { NextPageWithLayout, Organization } from 'types'
/**
* Variations of the Vercel integration flow.
@@ -36,7 +35,6 @@ export type VercelIntegrationFlow = 'deploy-button' | 'marketing'
const VercelIntegration: NextPageWithLayout = () => {
const router = useRouter()
- const { ui } = useStore()
const { code, configurationId, teamId, source, externalId } = useParams()
const [selectedOrg, setSelectedOrg] = useState<Organization | null>(null)
@@ -139,22 +137,19 @@ const VercelIntegration: NextPageWithLayout = () => {
const isIntegrationInstalled = orgSlug ? installed[orgSlug] : false
if (!orgSlug) {
- return ui.setNotification({ category: 'error', message: 'Please select an organization' })
+ return toast.error('Please select an organization')
}
if (!code) {
- return ui.setNotification({ category: 'error', message: 'Vercel code missing' })
+ return toast.error('Vercel code missing')
}
if (!configurationId) {
- return ui.setNotification({ category: 'error', message: 'Vercel Configuration ID missing' })
+ return toast.error('Vercel Configuration ID missing')
}
if (!source) {
- return ui.setNotification({
- category: 'error',
- message: 'Vercel Configuration source missing',
- })
+ return toast.error('Vercel Configuration source missing')
}
/**
diff --git a/apps/studio/pages/join/index.tsx b/apps/studio/pages/join/index.tsx
index f5963e36f93..89be3ea773a 100644
--- a/apps/studio/pages/join/index.tsx
+++ b/apps/studio/pages/join/index.tsx
@@ -2,6 +2,7 @@ import { useParams } from 'common'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
+import toast from 'react-hot-toast'
import { Button, IconCheckSquare, Loading } from 'ui'
import { useOrganizationJoinDeclineMutation } from 'data/organizations/organization-join-decline-mutation'
@@ -10,14 +11,12 @@ import {
TokenInfo,
validateTokenInformation,
} from 'data/organizations/organization-join-token-validation-query'
-import { useStore } from 'hooks'
import { useSignOut } from 'lib/auth'
import { useProfile } from 'lib/profile'
const JoinOrganizationPage = () => {
const router = useRouter()
const { slug, token, name } = useParams()
- const { ui } = useStore()
const { profile } = useProfile()
const signOut = useSignOut()
@@ -36,11 +35,7 @@ const JoinOrganizationPage = () => {
router.push('/')
},
onError: (error) => {
- ui.setNotification({
- error,
- category: 'error',
- message: `Failed to join organization: ${error.message}`,
- })
+ toast.error(`Failed to join organization: ${error.message}`)
setIsSubmitting(false)
},
})
@@ -51,11 +46,7 @@ const JoinOrganizationPage = () => {
router.push('/')
},
onError: (error) => {
- ui.setNotification({
- error,
- category: 'error',
- message: `Failed to decline invitation: ${error.message}`,
- })
+ toast.error(`Failed to decline invitation: ${error.message}`)
setIsSubmitting(false)
},
})
diff --git a/apps/studio/pages/new/[slug].tsx b/apps/studio/pages/new/[slug].tsx
index 9325a1c8c81..6176128b3a3 100644
--- a/apps/studio/pages/new/[slug].tsx
+++ b/apps/studio/pages/new/[slug].tsx
@@ -5,15 +5,19 @@ import { debounce } from 'lodash'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { PropsWithChildren, useEffect, useRef, useState } from 'react'
+import toast from 'react-hot-toast'
+import { Badge, Button, IconExternalLink, IconUsers, Input, Listbox } from 'ui'
import {
FreeProjectLimitWarning,
NotOrganizationOwnerWarning,
} from 'components/interfaces/Organization/NewProject'
import { RegionSelector } from 'components/interfaces/ProjectCreation/RegionSelector'
+import { WizardLayoutWithoutAuth } from 'components/layouts/WizardLayout'
import DisabledWarningDueToIncident from 'components/ui/DisabledWarningDueToIncident'
import Panel from 'components/ui/Panel'
import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'
+import type { components } from 'data/api'
import { useFreeProjectLimitCheckQuery } from 'data/organizations/free-project-limit-check-query'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
import {
@@ -22,7 +26,7 @@ import {
useProjectCreateMutation,
} from 'data/projects/project-create-mutation'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useCheckPermissions, useFlag, useStore, withAuth } from 'hooks'
+import { useCheckPermissions, useFlag, withAuth } from 'hooks'
import {
AWS_REGIONS,
CloudProvider,
@@ -34,16 +38,12 @@ import {
} from 'lib/constants'
import { passwordStrength, pluckObjectFields } from 'lib/helpers'
import type { NextPageWithLayout } from 'types'
-import { Badge, Button, IconExternalLink, IconUsers, Input, Listbox } from 'ui'
-import type { components } from 'data/api'
-import { WizardLayoutWithoutAuth } from 'components/layouts/WizardLayout'
type DesiredInstanceSize = components['schemas']['DesiredInstanceSize']
const Wizard: NextPageWithLayout = () => {
const router = useRouter()
const { slug } = useParams()
- const { ui } = useStore()
const projectCreationDisabled = useFlag('disableProjectCreationAndUpdate')
const cloudProviderEnabled = useFlag('enableFlyCloudProvider')
@@ -128,9 +128,9 @@ const Wizard: NextPageWithLayout = () => {
useEffect(() => {
// User added a new payment method
if (router.query.setup_intent && router.query.redirect_status) {
- ui.setNotification({ category: 'success', message: 'Successfully added new payment method' })
+ toast.success('Successfully added new payment method')
}
- }, [router.query.redirect_status, router.query.setup_intent, ui])
+ }, [router.query.redirect_status, router.query.setup_intent])
function onProjectNameChange(e: any) {
e.target.value = e.target.value.replace(/\./g, '')
@@ -179,10 +179,9 @@ const Wizard: NextPageWithLayout = () => {
}
if (postgresVersion) {
if (!postgresVersion.match(/1[2-9]\..*/)) {
- return ui.setNotification({
- category: 'error',
- message: `Invalid Postgres version, should start with a number between 12-19, a dot and additional characters, i.e. 15.2 or 15.2.0-3`,
- })
+ toast.error(
+ `Invalid Postgres version, should start with a number between 12-19, a dot and additional characters, i.e. 15.2 or 15.2.0-3`
+ )
}
data['customSupabaseRequest'] = {
diff --git a/apps/studio/stores/RootStore.ts b/apps/studio/stores/RootStore.ts
deleted file mode 100644
index 0f59e15a128..00000000000
--- a/apps/studio/stores/RootStore.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { configure } from 'mobx'
-
-import type { Project } from 'data/projects/project-detail-query'
-import UiStore, { IUiStore } from './UiStore'
-import MetaStore, { IMetaStore } from './pgmeta/MetaStore'
-
-// Temporary disable mobx warnings
-// TODO: need to remove this after refactoring old stores.
-configure({
- enforceActions: 'never',
-})
-
-export interface IRootStore {
- ui: IUiStore
- meta: IMetaStore
-
- setProject: (project: Project) => void
-}
-export class RootStore implements IRootStore {
- ui: IUiStore
- meta: IMetaStore
-
- constructor() {
- this.ui = new UiStore(this)
- this.meta = new MetaStore(this, { projectRef: '', connectionString: '' })
- }
-
- /**
- * Set selected project reference
- *
- * This method will also trigger project detail loading when it's not available
- */
- setProject(project: Project) {
- this.meta.setProjectDetails(project)
- // ui set must come last
- this.ui.setProjectRef(project.ref)
- }
-}
diff --git a/apps/studio/stores/UiStore.ts b/apps/studio/stores/UiStore.ts
index 345bbbb3fa8..475fe3f08f9 100644
--- a/apps/studio/stores/UiStore.ts
+++ b/apps/studio/stores/UiStore.ts
@@ -1,38 +1,17 @@
-import { action, makeAutoObservable } from 'mobx'
+import { makeAutoObservable } from 'mobx'
import { uuidv4 } from 'lib/helpers'
import type { Notification } from 'types'
-import type { IRootStore } from './RootStore'
export interface IUiStore {
- language: 'en-US'
- selectedProjectRef?: string
notification?: Notification
- setProjectRef: (ref?: string) => void
- setOrganizationSlug: (slug?: string) => void
setNotification: (notification: Notification) => string
}
export default class UiStore implements IUiStore {
- rootStore: IRootStore
- language: 'en-US' = 'en-US'
- selectedProjectRef?: string
- selectedOrganizationSlug?: string
notification?: Notification
- constructor(rootStore: IRootStore) {
- this.rootStore = rootStore
- makeAutoObservable(this, {
- setProjectRef: action,
- setOrganizationSlug: action,
- })
- }
-
- setProjectRef(ref?: string) {
- this.selectedProjectRef = ref
- }
-
- setOrganizationSlug(slug?: string) {
- this.selectedOrganizationSlug = slug
+ constructor() {
+ makeAutoObservable(this)
}
setNotification(notification: Notification): string {
diff --git a/apps/studio/stores/index.ts b/apps/studio/stores/index.ts
deleted file mode 100644
index 05f112c22e5..00000000000
--- a/apps/studio/stores/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './RootStore'
diff --git a/apps/studio/stores/pgmeta/MetaStore.ts b/apps/studio/stores/pgmeta/MetaStore.ts
deleted file mode 100644
index 87b23323129..00000000000
--- a/apps/studio/stores/pgmeta/MetaStore.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { makeObservable } from 'mobx'
-
-import { post } from 'lib/common/fetch'
-import { API_URL, IS_PLATFORM } from 'lib/constants'
-import type { ResponseError } from 'types'
-
-import type { IRootStore } from '../RootStore'
-
-export interface IMetaStore {
- projectRef?: string
- connectionString?: string
-
- query: (value: string) => Promise<any | { error: ResponseError }>
- validateQuery: (value: string) => Promise<any | { error: ResponseError }>
- formatQuery: (value: string) => Promise<any | { error: ResponseError }>
-
- setProjectDetails: (details: { ref: string; connectionString?: string }) => void
-}
-export default class MetaStore implements IMetaStore {
- rootStore: IRootStore
-
- projectRef: string
- connectionString?: string
- baseUrl: string
- headers: { [prop: string]: any }
-
- constructor(rootStore: IRootStore, options: { projectRef: string; connectionString?: string }) {
- const { projectRef, connectionString } = options
- this.rootStore = rootStore
- this.projectRef = projectRef
- this.baseUrl = `${API_URL}/pg-meta/${projectRef}`
-
- this.headers = {}
- if (IS_PLATFORM && connectionString) {
- this.connectionString = connectionString
- this.headers['x-connection-encrypted'] = connectionString
- }
-
- makeObservable(this, {})
- }
-
- /**
- * Sends a database query
- */
- async query(value: string) {
- try {
- const headers: any = { 'Content-Type': 'application/json' }
- if (this.connectionString) headers['x-connection-encrypted'] = this.connectionString
- const url = `${this.baseUrl}/query`
- const response = await post(url, { query: value }, { headers })
- if (response.error) throw response.error
-
- return response
- } catch (error: any) {
- return { error }
- }
- }
-
- async validateQuery(value: string) {
- try {
- const headers: any = { 'Content-Type': 'application/json' }
- if (this.connectionString) headers['x-connection-encrypted'] = this.connectionString
- const url = `${this.baseUrl}/query/validate`
- const response = await post(url, { query: value }, { headers })
- if (response.error) throw response.error
-
- return response
- } catch (error: any) {
- return { error }
- }
- }
-
- async formatQuery(value: string) {
- try {
- const headers: any = { 'Content-Type': 'application/json' }
- if (this.connectionString) headers['x-connection-encrypted'] = this.connectionString
- const url = `${this.baseUrl}/query/format`
- const response = await post(url, { query: value }, { headers })
- if (response.error) throw response.error
-
- return response
- } catch (error: any) {
- return { error }
- }
- }
-
- setProjectDetails({ ref, connectionString }: { ref: string; connectionString?: string }) {
- this.projectRef = ref
- this.baseUrl = `${API_URL}/pg-meta/${ref}`
- if (IS_PLATFORM && connectionString) {
- this.connectionString = connectionString
- this.headers['x-connection-encrypted'] = connectionString
- }
- }
-}
diff --git a/apps/studio/styles/grid.scss b/apps/studio/styles/grid.scss
index 592079fd88f..8ed060f0e90 100644
--- a/apps/studio/styles/grid.scss
+++ b/apps/studio/styles/grid.scss
@@ -170,7 +170,7 @@
}
[type='checkbox']:checked {
- background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");
+ background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='black' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");
}
[type='checkbox']:checked {
@@ -185,7 +185,7 @@
@apply cursor-pointer rounded border border-solid;
@apply text-foreground border-default transition-all;
- @apply hover:border-foreground focus:ring-foreground focus:outline-none;
+ @apply hover:border-foreground focus:ring-0 focus:outline-none;
@apply bg-transparent;
diff --git a/apps/studio/tests/helpers.tsx b/apps/studio/tests/helpers.tsx
index 1ff5da2926a..9e60805c266 100644
--- a/apps/studio/tests/helpers.tsx
+++ b/apps/studio/tests/helpers.tsx
@@ -1,11 +1,11 @@
-import { screen, getByText, fireEvent } from '@testing-library/react'
+import { fireEvent, getByText, screen } from '@testing-library/react'
import React, { useState } from 'react'
+import { TooltipProvider } from '@radix-ui/react-tooltip'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render as originalRender } from '@testing-library/react'
-import { RootStore } from 'stores'
import { StoreProvider } from 'hooks'
-import { TooltipProvider } from '@radix-ui/react-tooltip'
+import UiStore from 'stores/UiStore'
interface SelectorOptions {
container?: HTMLElement
}
@@ -48,7 +48,7 @@ export const clickDropdown = (elem: HTMLElement) => {
* https://testing-library.com/docs/react-testing-library/setup/#custom-render
*/
const ReactQueryTestConfig: React.FC<React.PropsWithChildren> = ({ children }) => {
- const [rootStore] = useState(() => new RootStore())
+ const [rootStore] = useState(() => ({ ui: new UiStore() }))
const [queryClient] = useState(
() =>