Skip to content

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

adds basic migrations on (vercel) project creation

Alaister Youngb21072929edf
diff --git a/studio/data/projects/project-create-mutation.ts b/studio/data/projects/project-create-mutation.ts
index a813f4d5d64..f355ee965f4 100644
--- a/studio/data/projects/project-create-mutation.ts
+++ b/studio/data/projects/project-create-mutation.ts
@@ -9,6 +9,7 @@ export type ProjectCreateVariables = {
organizationId: number
dbPass: string
dbRegion: string
+ dbSql?: string
configurationId?: string
}
@@ -17,6 +18,7 @@ export async function createProject({
organizationId,
dbPass,
dbRegion,
+ dbSql,
configurationId,
}: ProjectCreateVariables) {
const response = await post(`${API_URL}/projects`, {
@@ -25,7 +27,7 @@ export async function createProject({
name,
db_pass: dbPass,
db_region: dbRegion,
- // db_sql: dbSql || '',
+ db_sql: dbSql,
db_pricing_tier_id: PRICING_TIER_PRODUCT_IDS.FREE,
// auth_site_url: _store.selectedVercelProjectUrl,
vercel_configuration_id: configurationId,
diff --git a/studio/lib/integration-utils.ts b/studio/lib/integration-utils.ts
new file mode 100644
index 00000000000..8336470c685
--- /dev/null
+++ b/studio/lib/integration-utils.ts
@@ -0,0 +1,87 @@
+import { ResponseFailure } from 'types'
+
+type SupaResponse<T> = T | ResponseFailure
+
+async function fetchGitHub<T = any>(url: string, responseJson = true): Promise<SupaResponse<T>> {
+ const response = await fetch(url)
+ if (!response.ok) {
+ return {
+ error: {
+ code: response.status,
+ message: response.statusText,
+ requestId: '',
+ },
+ }
+ }
+ try {
+ return (responseJson ? await response.json() : await response.text()) as T
+ } catch (error: any) {
+ return {
+ error: {
+ message: error.message,
+ code: 500,
+ requestId: '',
+ },
+ }
+ }
+}
+
+export type File = {
+ name: string
+ download_url: string
+}
+
+/**
+ * Returns the initial migration SQL from a GitHub repo.
+ * @param externalId An external GitHub URL for example: https://github.com/vercel/next.js/tree/canary/examples/with-supabase
+ */
+export async function getInitialMigrationSQLFromGitHubRepo(
+ externalId?: string
+): Promise<string | null> {
+ if (!externalId) return null
+
+ const [, , , owner, repo, , branch, ...pathSegments] = externalId?.split('/') ?? []
+ const path = pathSegments.join('/')
+
+ const baseGitHubUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`
+ const supabaseFolderUrl = `${baseGitHubUrl}/supabase?ref=${branch}`
+ const supabaseMigrationsPath = `supabase/migrations` // TODO: read this from the `supabase/config.toml` file
+ const migrationsFolderUrl = `${baseGitHubUrl}/${supabaseMigrationsPath}?ref=${branch}`
+
+ const [supabaseFilesResponse, migrationFilesResponse] = await Promise.all([
+ fetchGitHub<File[]>(supabaseFolderUrl),
+ fetchGitHub<File[]>(migrationsFolderUrl),
+ ])
+
+ if ('error' in supabaseFilesResponse) {
+ console.warn(`Failed to fetch supabase files from GitHub: ${supabaseFilesResponse.error}`)
+ return null
+ }
+ if ('error' in migrationFilesResponse) {
+ console.warn(`Failed to fetch migration files from GitHub: ${migrationFilesResponse.error}`)
+ return null
+ }
+
+ const seedFileUrl = supabaseFilesResponse.find((file) => file.name === 'seed.sql')?.download_url
+ const migrationFileDownloadUrlPromises = migrationFilesResponse
+ .sort((a, b) => {
+ // sort by name ascending
+ if (a.name < b.name) return -1
+ if (a.name > b.name) return 1
+ return 0
+ })
+ .map((file) => fetchGitHub<string>(file.download_url, false))
+
+ const [seedFileResponse, ...migrationFileResponses] = await Promise.all([
+ seedFileUrl ? fetchGitHub<string>(seedFileUrl, false) : Promise.resolve<string>(''),
+ ...migrationFileDownloadUrlPromises,
+ ])
+
+ const migrations = migrationFileResponses
+ .filter((response) => !(typeof response === 'object' && 'error' in response))
+ .join(';')
+ const seed =
+ typeof seedFileResponse === 'object' && 'error' in seedFileResponse ? '' : seedFileResponse
+
+ return `${migrations};${seed}`
+}
diff --git a/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx b/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
index 538d2d3381a..eb82bd7245f 100644
--- a/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
+++ b/studio/pages/integrations/vercel/[slug]/deploy-button/new-project.tsx
@@ -7,6 +7,7 @@ import { Markdown } from 'components/interfaces/Markdown'
import IntegrationWindowLayout from 'components/layouts/IntegrationWindowLayout'
import { ScaffoldContainer, ScaffoldDivider } from 'components/layouts/Scaffold'
import PasswordStrengthBar from 'components/ui/PasswordStrengthBar'
+import { useProjectApiQuery } from 'data/config/project-api-query'
import { useIntegrationConnectionsCreateMutation } from 'data/integrations/integration-connections-create-mutation'
import { useIntegrationsQuery } from 'data/integrations/integrations-query'
import { useVercelProjectsQuery } from 'data/integrations/integrations-vercel-projects-query'
@@ -17,9 +18,9 @@ import generator from 'generate-password'
import { useStore } 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 { NextPageWithLayout, ProjectBase } from 'types'
-import { Alert, Button, IconBook, IconLifeBuoy, Input, Listbox, LoadingLine } from 'ui'
-import { useProjectApiQuery } from 'data/config/project-api-query'
+import { Alert, Button, Checkbox, IconBook, IconLifeBuoy, Input, Listbox, LoadingLine } from 'ui'
const VercelIntegration: NextPageWithLayout = () => {
const [loading, setLoading] = useState<boolean>(false)
@@ -75,21 +76,25 @@ const CreateProject = ({
const [dbPass, setDbPass] = useState('')
const [passwordStrengthMessage, setPasswordStrengthMessage] = useState('')
const [passwordStrengthScore, setPasswordStrengthScore] = useState(-1)
+ const [shouldRunMigrations, setShouldRunMigrations] = useState(true)
const [dbRegion, setDbRegion] = useState(PROVIDERS.AWS.default_region)
// const [loading, setLoading] = useState(false)
const delayedCheckPasswordStrength = useRef(
debounce((value: string) => checkPasswordStrength(value), 300)
).current
- const { configurationId, next, currentProjectId: foreignProjectId } = useParams()
+ const {
+ slug,
+ configurationId,
+ next,
+ currentProjectId: foreignProjectId,
+ externalId,
+ } = useParams()
const { mutateAsync: createConnections, isLoading: isLoadingCreateConnections } =
useIntegrationConnectionsCreateMutation({})
const { data: organizationData, isLoading: isLoadingOrganizationsQuery } = useOrganizationsQuery()
- const { slug } = router.query
-
- console.log('slug')
const organization = organizationData?.find((x) => x.slug === slug)
@@ -115,8 +120,6 @@ const CreateProject = ({
{ enabled: organizationIntegration !== undefined }
)
- console.log('vercelProjects near top', vercelProjects)
-
const canSubmit =
projectName != '' &&
passwordStrengthScore >= DEFAULT_MINIMUM_PASSWORD_STRENGTH &&
@@ -179,6 +182,23 @@ const CreateProject = ({
throw new Error('No organization set')
}
+ let dbSql: string | undefined
+ if (shouldRunMigrations) {
+ const id = ui.setNotification({
+ category: 'info',
+ message: `Fetching initial migrations from GitHub repo`,
+ })
+
+ dbSql = (await getInitialMigrationSQLFromGitHubRepo(externalId)) ?? undefined
+
+ ui.setNotification({
+ id,
+ category: 'success',
+ message: `Done fetching initial migrations`,
+ })
+ }
+ console.log('dbSql:', dbSql)
+
let project: ProjectBase
try {
@@ -187,6 +207,7 @@ const CreateProject = ({
name: projectName,
dbPass,
dbRegion,
+ dbSql,
configurationId,
})
@@ -297,7 +318,7 @@ const CreateProject = ({
}
/>
</div>
- <div className="py-2 pb-4">
+ <div className="py-2">
<div className="mt-1">
<Listbox
label="Region"
@@ -328,6 +349,15 @@ const CreateProject = ({
</Listbox>
</div>
</div>
+ <div className="py-2 pb-4">
+ <Checkbox
+ name="shouldRunMigrations"
+ label="Run migrations & seed.sql"
+ description="If your repository has migrations under supabase/migrations, they will be run automatically."
+ checked={shouldRunMigrations}
+ onChange={(e) => setShouldRunMigrations(e.target.checked)}
+ />
+ </div>
<div className="flex flex-row w-full justify-end">
<Button
size="medium"
@@ -339,9 +369,6 @@ const CreateProject = ({
Create Project
</Button>
</div>
- {/* <Button disabled={loading || !canSubmit} loading={loading} onClick={onCreateProject}>
- Create project
- </Button> */}
</div>
)
}
diff --git a/studio/pages/integrations/vercel/[slug]/marketplace/choose-project.tsx b/studio/pages/integrations/vercel/[slug]/marketplace/choose-project.tsx
index cae0c637d86..afbbc25646e 100644
--- a/studio/pages/integrations/vercel/[slug]/marketplace/choose-project.tsx
+++ b/studio/pages/integrations/vercel/[slug]/marketplace/choose-project.tsx
@@ -2,7 +2,6 @@ import { useMemo, useState } from 'react'
import { useParams } from 'common'
import ProjectLinker from 'components/interfaces/Integrations/ProjectLinker'
-
import { Markdown } from 'components/interfaces/Markdown'
import IntegrationWindowLayout from 'components/layouts/IntegrationWindowLayout'
import { ScaffoldContainer, ScaffoldDivider } from 'components/layouts/Scaffold'
@@ -10,27 +9,22 @@ import { useOrgIntegrationsQuery } from 'data/integrations/integrations-query-or
import { useVercelProjectsQuery } from 'data/integrations/integrations-vercel-projects-query'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
import { useProjectsQuery } from 'data/projects/projects-query'
-import { useStore } from 'hooks'
import { EMPTY_ARR } from 'lib/void'
-import { useRouter } from 'next/router'
import { NextPageWithLayout, Organization } from 'types'
import { IconBook, IconLifeBuoy, LoadingLine } from 'ui'
const VercelIntegration: NextPageWithLayout = () => {
- const router = useRouter()
- const { configurationId, next, organizationSlug } = useParams()
+ const { slug, configurationId, next, organizationSlug } = useParams()
const [loading, setLoading] = useState<boolean>(false)
- const { slug } = router.query
-
/**
* Fetch the list of organization based integration installations for Vercel.
*
* Array of integrations installed on all
*/
const { data: integrationData, isLoading: integrationDataLoading } = useOrgIntegrationsQuery({
- orgSlug: slug?.toString(),
+ orgSlug: slug,
})
const { data, isLoading: isLoadingOrganizationsQuery } = useOrganizationsQuery({