Skip to content

Commit

Permalink
feat: apply migrations in pages ci
Browse files Browse the repository at this point in the history
  • Loading branch information
RihanArfan committed Oct 23, 2024
1 parent 3c59920 commit 8f22d22
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/utils/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import { useRuntimeConfig, logger } from '@nuxt/kit'
const log = logger.withTag('nuxt:hub')

export const runMigrations = async () => {
const srcStorage = useMigrationsStorage()
await createMigrationsTable()

log.info('Checking for pending migrations...')
const remoteMigrations = await getRemoteMigrations().catch((error) => {
log.error(`Could not retrieve migrations on ${process.env.NUXT_HUB_ENV}.`)
if (error) log.error(error)
Expand All @@ -17,9 +19,29 @@ export const runMigrations = async () => {
if (!remoteMigrations.length) log.warn(`No applied migrations on ${process.env.NUXT_HUB_ENV}.`)

const localMigrations = (await getMigrationFiles()).map(fileName => fileName.replace('.sql', ''))

const pendingMigrations = localMigrations.filter(localName => !remoteMigrations.find(({ name }) => name === localName))
if (!pendingMigrations.length) log.info('No pending migrations to apply.')
if (!pendingMigrations.length) return log.info('No pending migrations to apply.')

log.info('Applying migrations...')
for (const migration of pendingMigrations) {
const migrationFile = await srcStorage.getItemRaw(`${migration}.sql`)
let query = migrationFile.toString()

if (query.at(-1) !== ';') query += ';' // ensure previous statement ended before running next query
query += `
INSERT INTO hub_migrations (name) values ('${migration}');
`

try {
await useDatabaseQuery(query)
} catch (error: any) {
log.error(`Failed to apply migration \`${migration}\`.`)
if (error && error.response) log.error(error.response?._data?.message || error)
break
}

log.success(`Applied migration \`${migration}\`.`)
}
}

export const useDatabaseQuery = async <T>(query: string) => {
Expand Down

0 comments on commit 8f22d22

Please sign in to comment.