The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Implement branch switching logic
Joshen Lim06de0750e3a3
diff --git a/studio/components/interfaces/BranchManagement/BranchManagement.tsx b/studio/components/interfaces/BranchManagement/BranchManagement.tsxindex 012f82d1cf7..adbca4688e1 100644--- a/studio/components/interfaces/BranchManagement/BranchManagement.tsx+++ b/studio/components/interfaces/BranchManagement/BranchManagement.tsx@@ -9,12 +9,18 @@ import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'import { useBranchDeleteMutation } from 'data/branches/branch-delete-mutation'import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'import { Branch, useBranchesQuery } from 'data/branches/branches-query'-import { useStore } from 'hooks'+import { useSelectedProject, useStore } from 'hooks'import { BranchHeader, BranchPanel } from './BranchPanels'const BranchManagement = () => {const { ui } = useStore()- const { ref: projectRef } = useParams()+ const { ref } = useParams()+ const projectDetails = useSelectedProject()++ const isBranch = projectDetails?.parent_project_ref !== undefined+ const projectRef =+ projectDetails !== undefined ? (isBranch ? projectDetails.parent_project_ref : ref) : undefined+const [selectedBranchToUpdate, setSelectedBranchToUpdate] = useState<Branch>()const [selectedBranchToDelete, setSelectedBranchToDelete] = useState<Branch>()diff --git a/studio/components/interfaces/BranchManagement/BranchPanels.tsx b/studio/components/interfaces/BranchManagement/BranchPanels.tsxindex 92667e38dc1..c39052f64c1 100644--- a/studio/components/interfaces/BranchManagement/BranchPanels.tsx+++ b/studio/components/interfaces/BranchManagement/BranchPanels.tsx@@ -41,7 +41,7 @@ const BranchPanel = ({if (branch?.is_default) {return (- <div className="bg-scale-300 border shadow-sm flex justify-between items-center pl-8 pr-6 py-4 rounded-lg text-sm">+ <div className="bg-surface-100 border shadow-sm flex justify-between items-center pl-8 pr-6 py-4 rounded-lg text-sm"><div className="flex items-center space-x-4"><IconShield size={16} strokeWidth={2} /><p>{branch?.name}</p>@@ -71,7 +71,7 @@ const BranchPanel = ({return (<li className="list-none ml-6 pl-8 pb-4 border-l border-scale-600 dark:border-scale-400 relative last:!border-transparent"><div className="absolute w-[33px] rounded-bl-full border-b border-l border-scale-600 dark:border-scale-400 h-10 -left-px" />- <div className="bg-scale-300 border shadow-sm flex justify-between items-center pl-8 pr-6 py-4 rounded-lg text-sm">+ <div className="bg-surface-100 border shadow-sm flex justify-between items-center pl-8 pr-6 py-4 rounded-lg text-sm"><div className="flex items-center space-x-4"><IconGitBranch className="text-brand-900" size={16} strokeWidth={2} /><p>{branch?.name}</p>diff --git a/studio/components/layouts/AppLayout/AppHeader.tsx b/studio/components/layouts/AppLayout/AppHeader.tsxindex 8879ac701d5..e6bcbe9bca9 100644--- a/studio/components/layouts/AppLayout/AppHeader.tsx+++ b/studio/components/layouts/AppLayout/AppHeader.tsx@@ -2,7 +2,7 @@ import Link from 'next/link'import { useRouter } from 'next/router'import { useParams } from 'common'-import { useSelectedOrganization } from 'hooks'+import { useFlag, useSelectedOrganization } from 'hooks'import FeedbackDropdown from '../ProjectLayout/LayoutHeader/FeedbackDropdown'import HelpPopover from '../ProjectLayout/LayoutHeader/HelpPopover'import NotificationsPopover from '../ProjectLayout/LayoutHeader/NotificationsPopover'@@ -16,6 +16,7 @@ const AppHeader = () => {const router = useRouter()const { ref } = useParams()const organization = useSelectedOrganization()+ const enableBranchManagement = useFlag('branchManagement')return (<div className="flex items-center justify-between px-4 py-1 bg-scale-200 border-b">@@ -31,7 +32,7 @@ const AppHeader = () => {</Link><OrganizationDropdown />{ref !== undefined && <ProjectDropdown />}- {ref !== undefined && <BranchDropdown />}+ {ref !== undefined && enableBranchManagement && <BranchDropdown />}</div><div className="flex items-center gap-4">diff --git a/studio/components/layouts/AppLayout/BranchDropdown.tsx b/studio/components/layouts/AppLayout/BranchDropdown.tsxindex 47c8b62150c..adbbf63d607 100644--- a/studio/components/layouts/AppLayout/BranchDropdown.tsx+++ b/studio/components/layouts/AppLayout/BranchDropdown.tsx@@ -21,20 +21,22 @@ import {PopoverTrigger_Shadcn_,Popover_Shadcn_,} from 'ui'+import { useSelectedProject } from 'hooks'const BranchDropdown = () => {const router = useRouter()- const { ref: projectRef } = useParams()+ const { ref } = useParams()+ const projectDetails = useSelectedProject()const branchNameRef = useRef<HTMLAnchorElement>(null)++ const isBranch = projectDetails?.parent_project_ref !== undefined+ const projectRef =+ projectDetails !== undefined ? (isBranch ? projectDetails.parent_project_ref : ref) : undefinedconst { data: branches, isLoading, isError, isSuccess } = useBranchesQuery({ projectRef })const [open, setOpen] = useState(false)const popoverOffset = (branchNameRef.current?.offsetWidth ?? 0) + 12- const selectedBranch = branches?.find((branch) => branch.project_ref === projectRef)-- const onSwitchBranch = async () => {- console.log('Fetch branch details and update connection string or something')- }+ const selectedBranch = branches?.find((branch) => branch.project_ref === ref)return (<>@@ -47,7 +49,11 @@ const BranchDropdown = () => {<Link passHref href={`/project/${projectRef}/branches`}><a ref={branchNameRef} className="flex items-center space-x-2"><p className="text-sm">{selectedBranch?.name}</p>- {selectedBranch?.is_default && <Badge color="amber">Production</Badge>}+ {selectedBranch?.is_default ? (+ <Badge color="amber">Production</Badge>+ ) : (+ <Badge color="green">Branch</Badge>+ )}</a></Link>@@ -84,11 +90,9 @@ const BranchDropdown = () => {className="cursor-pointer w-full flex items-center justify-between"onSelect={() => {setOpen(false)- onSwitchBranch()router.push(href)}}onClick={() => {- onSwitchBranch()setOpen(false)}}>diff --git a/studio/components/layouts/AppLayout/ProjectDropdown.tsx b/studio/components/layouts/AppLayout/ProjectDropdown.tsxindex 411531e687e..70cba5c7c7e 100644--- a/studio/components/layouts/AppLayout/ProjectDropdown.tsx+++ b/studio/components/layouts/AppLayout/ProjectDropdown.tsx@@ -106,7 +106,10 @@ const ProjectDropdown = () => {const projectNameRef = useRef<HTMLAnchorElement>(null)const { data: allProjects, isLoading: isLoadingProjects } = useProjectsQuery()- console.log({ selectedProject })+ const isBranch = projectDetails?.parent_project_ref !== undefined+ const parentProject = isBranch+ ? allProjects?.find((project) => project.ref === projectDetails.parent_project_ref)+ : undefinedconst isOrgBilling = !!selectedOrganization?.subscription_idconst { data: subscription, isSuccess } = useProjectSubscriptionV2Query(@@ -117,7 +120,9 @@ const ProjectDropdown = () => {?.filter((x) => x.status !== PROJECT_STATUS.INACTIVE).filter((x) => x.organization_id === selectedOrganization?.id).sort((a, b) => a.name.localeCompare(b.name))- const selectedProject = projectDetails || projects?.find((project) => project.ref === ref)+ const selectedProject = isBranch+ ? parentProject+ : projectDetails || projects?.find((project) => project.ref === ref)const [open, setOpen] = useState(false)const popoverOffset = (projectNameRef.current?.offsetWidth ?? 0) + 12diff --git a/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx b/studio/components/layouts/AppLayout/UserSettingsDropdown.tsxindex 9a52dda2c84..51bba7ff4d7 100644--- a/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx+++ b/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx@@ -1,4 +1,4 @@-import Link from 'components/ui/ProjectLink'+import Link from 'next/link'import { useRouter } from 'next/router'import {DropdownMenuContent_Shadcn_,diff --git a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/studio/components/layouts/ProjectLayout/ProjectLayout.tsxindex 4b23582c1ef..10116f2f31f 100644--- a/studio/components/layouts/ProjectLayout/ProjectLayout.tsx+++ b/studio/components/layouts/ProjectLayout/ProjectLayout.tsx@@ -29,6 +29,8 @@ const routesToIgnoreProjectDetailsRequest = ['/project/[ref]/settings/billing/invoices',]+const routesToIgnoreDBConnection = ['/project/[ref]/branches']+const routesToIgnorePostgrestConnection = ['/project/[ref]/reports','/project/[ref]/settings/general',@@ -161,8 +163,9 @@ const ContentWrapper = ({ isLoading, children }: ContentWrapperProps) => {const router = useRouter()const requiresDbConnection: boolean =- !router.pathname.includes('/project/[ref]/settings') ||- router.pathname.includes('/project/[ref]/settings/vault')+ (!router.pathname.includes('/project/[ref]/settings') &&+ !routesToIgnoreDBConnection.includes(router.pathname)) ||+ router.pathname === '/project/[ref]/settings/vault'const requiresPostgrestConnection = !routesToIgnorePostgrestConnection.includes(router.pathname)const requiresProjectDetails = !routesToIgnoreProjectDetailsRequest.includes(router.pathname)diff --git a/studio/components/ui/ProjectLink.tsx b/studio/components/ui/ProjectLink.tsxdeleted file mode 100644index 5e956142497..00000000000--- a/studio/components/ui/ProjectLink.tsx+++ /dev/null@@ -1,103 +0,0 @@-import NextLink, { LinkProps as NextLinkProps } from 'next/link'-import { useRouter } from 'next/router'-import { forwardRef, PropsWithChildren, PropsWithoutRef, useMemo } from 'react'--export type Override<T1, T2> = Omit<T1, keyof T2> & T2--function isValidUrl(urlString: string) {- try {- return Boolean(new URL(urlString))- } catch (e) {- return false- }-}--const ProjectLink = forwardRef<- HTMLAnchorElement,- Override<- Override<PropsWithoutRef<JSX.IntrinsicElements['a']>, NextLinkProps>,- PropsWithChildren<{}>- >->(- (- {- href,- as: nextAs,- prefetch,- replace,- scroll,- shallow,- children,- className: overrideClassName,- ...props- },- ref- ) => {- const { query } = useRouter()- const { branch } = query-- const hrefWithBranch = useMemo(() => {- if (typeof href === 'string') {- const url = isValidUrl(href)- ? new URL(href)- : new URL(`https://supabase.com/${href.replace(/^\//, '')}`)- const branchId = url.searchParams.get('branch')- url.searchParams.delete('branch')-- const existingSearchParams = [...url.searchParams.entries()].reduce(- (acc, [key, value]) => {- let temp = acc[key]- if (temp) {- if (Array.isArray(temp)) {- temp.push(value)- } else {- temp = [temp, value]- }- } else {- temp = value- }- acc[key] = temp- return acc- },- {} as {- [key: string]: string | string[]- }- )-- return {- pathname: url.pathname,- query: {- ...((branch !== undefined || branchId !== null) && { branch: branchId || branch }),- ...existingSearchParams,- },- }- } else {- return {- ...href,- query: { ...(branch !== undefined && { branch }), ...(href.query as object) },- }- }- }, [branch, href])-- return (- <NextLink- ref={ref}- {...{- href: hrefWithBranch,- as: nextAs,- prefetch,- replace,- scroll,- shallow,- className: overrideClassName,- ...props,- }}- >- {children}- </NextLink>- )- }-)--ProjectLink.displayName = 'ProjectLink'-export default ProjectLinkdiff --git a/studio/data/api.d.ts b/studio/data/api.d.tsindex 5a30a524614..8a16ffd26b7 100644--- a/studio/data/api.d.ts+++ b/studio/data/api.d.ts@@ -1489,7 +1489,6 @@ export interface paths {post: operations["OAuthAppsController_createOAuthApp"];};"/v1/organizations/{slug}/oauth/apps/{id}": {- get: operations["OAuthAppsController_getOAuthApp"];/** Update an oauth app */put: operations["OAuthAppsController_updateOAuthApp"];/** Remove a published oauth app */@@ -3154,6 +3153,7 @@ export interface components {maxDatabasePreprovisionGb?: number;lastDatabaseResizeAt?: string;preview_branches: (components["schemas"]["BranchResponse"])[];+ parent_project_ref?: string;};ProjectRefResponse: {id: number;@@ -4146,19 +4146,56 @@ export interface components {created_at?: string;updated_at?: string;};+ OAuthAppResponse: {+ id: string;+ name: string;+ website: string;+ icon?: string;+ authorized_at?: string;+ created_at?: string;+ client_id?: string;+ client_secret_alias?: string;+ redirect_uris?: (string)[];+ };CreateOAuthAppBody: {name: string;website: string;icon?: string;redirect_uris: (string)[];};- UpdateOAuthAppBody: {+ CreateOAuthAppResponse: {+ id: string;+ client_id: string;+ client_secret: string;+ };+ PutOAuthAppResponse: {+ id: string;+ client_id: string;+ client_secret_alias: string;+ created_at: string;name: string;website: string;+ icon?: string;redirect_uris: (string)[];+ };+ RevokeAuthorizedOAuthAppResponse: {+ id: string;+ name: string;+ website: string;+ icon?: string;+ authorized_at: string;+ };+ DeleteOAuthAppResponse: {+ id: string;+ name: string;+ website: string;icon?: string;+ created_at: string;+ client_id: string;+ client_secret_alias: string;+ redirect_uris: (string)[];};- TokenDTO: {+ OAuthTokenBody: {/** @enum {string} */grant_type: "authorization_code" | "refresh_token";client_id: string;@@ -4168,9 +4205,31 @@ export interface components {redirect_uri?: string;refresh_token?: string;};+ OAuthTokenResponse: {+ /** @enum {string} */+ token_type: "Bearer";+ access_token: string;+ refresh_token: string;+ expires_in: number;+ };+ GetAuthorizationResponse: {+ name: string;+ website: string;+ icon?: string;+ domain: string;+ expires_at: string;+ approved_at?: string;+ approved_organization_slug?: string;+ };AuthorizationsApproveBody: {organization_id: string;};+ ApproveAuthorizationResponse: {+ url: string;+ };+ DeclineAuthorizationResponse: {+ id: string;+ };};responses: never;parameters: never;@@ -9754,7 +9813,7 @@ export interface operations {responses: {200: {content: {- "application/json": Record<string, never>;+ "application/json": (components["schemas"]["OAuthAppResponse"])[];};};};@@ -9772,12 +9831,11 @@ export interface operations {};};responses: {- 201: never;- };- };- OAuthAppsController_getOAuthApp: {- responses: {- 200: never;+ 201: {+ content: {+ "application/json": components["schemas"]["CreateOAuthAppResponse"];+ };+ };};};/** Update an oauth app */@@ -9790,11 +9848,15 @@ export interface operations {};requestBody: {content: {- "application/json": components["schemas"]["UpdateOAuthAppBody"];+ "application/json": components["schemas"]["CreateOAuthAppBody"];};};responses: {- 200: never;+ 200: {+ content: {+ "application/json": components["schemas"]["PutOAuthAppResponse"];+ };+ };};};/** Remove a published oauth app */@@ -9806,7 +9868,11 @@ export interface operations {};};responses: {- 200: never;+ 200: {+ content: {+ "application/json": components["schemas"]["DeleteOAuthAppResponse"];+ };+ };};};/** Revoke an authorized oauth app */@@ -9818,7 +9884,11 @@ export interface operations {};};responses: {- 201: never;+ 201: {+ content: {+ "application/json": components["schemas"]["RevokeAuthorizedOAuthAppResponse"];+ };+ };};};/** Authorize user through oauth */@@ -9836,18 +9906,22 @@ export interface operations {};};responses: {- 200: never;+ 303: never;};};/** Exchange auth code for user's access and refresh token */OAuthController_token: {requestBody: {content: {- "application/x-www-form-urlencoded": components["schemas"]["TokenDTO"];+ "application/x-www-form-urlencoded": components["schemas"]["OAuthTokenBody"];};};responses: {- 201: never;+ 201: {+ content: {+ "application/json": components["schemas"]["OAuthTokenResponse"];+ };+ };};};AuthorizationsController_getAuthorizationRequest: {@@ -9857,7 +9931,11 @@ export interface operations {};};responses: {- 200: never;+ 200: {+ content: {+ "application/json": components["schemas"]["GetAuthorizationResponse"];+ };+ };};};/** Approve oauth app authorization request */@@ -9873,7 +9951,11 @@ export interface operations {};};responses: {- 201: never;+ 201: {+ content: {+ "application/json": components["schemas"]["ApproveAuthorizationResponse"];+ };+ };};};/** Decline oauth app authorization request */@@ -9884,7 +9966,11 @@ export interface operations {};};responses: {- 200: never;+ 200: {+ content: {+ "application/json": components["schemas"]["DeclineAuthorizationResponse"];+ };+ };};};}diff --git a/studio/data/branches/branches-query.ts b/studio/data/branches/branches-query.tsindex 6b8bfe4966c..b7dd3bf0042 100644--- a/studio/data/branches/branches-query.ts+++ b/studio/data/branches/branches-query.ts@@ -11,8 +11,10 @@ export type BranchesVariables = {export type Branch = components['schemas']['BranchResponse']export async function getBranches({ projectRef }: BranchesVariables, signal?: AbortSignal) {+ if (!projectRef) throw new Error('Project ref is required')+const { data, error } = await get(`/v1/projects/{ref}/branches`, {- params: { path: { ref: projectRef ?? '' } },+ params: { path: { ref: projectRef } },signal,})diff --git a/studio/types/base.ts b/studio/types/base.tsindex 706ea36740d..6cb3096544a 100644--- a/studio/types/base.ts+++ b/studio/types/base.ts@@ -22,6 +22,7 @@ export interface ProjectBase {region: stringinserted_at: stringsubscription_id: string+ preview_branches: any[]}export interface Project extends ProjectBase {@@ -32,6 +33,7 @@ export interface Project extends ProjectBase {restUrl?: stringlastDatabaseResizeAt?: string | nullmaxDatabasePreprovisionGb?: string | null+ parent_project_ref?: string/*** postgrestStatus is available on client side only.