-
Notifications
You must be signed in to change notification settings - Fork 449
feat: add db migrations reset command
#8177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| import { readdir, rm } from 'fs/promises' | ||
| import { join } from 'path' | ||
|
|
||
| import { chalk, log, logJson, netlifyCommand } from '../../utils/command-helpers.js' | ||
| import BaseCommand from '../base-command.js' | ||
| import { localAppliedMigrations, remoteAppliedMigrations } from './util/applied-migrations.js' | ||
| import { connectToDatabase } from './util/db-connection.js' | ||
| import { resolveMigrationsDirectory } from './util/migrations-path.js' | ||
|
|
||
| export interface MigrationsResetOptions { | ||
| branch?: string | ||
| json?: boolean | ||
| } | ||
|
|
||
| const SQL_EXTENSION = '.sql' | ||
|
|
||
| interface LocalMigration { | ||
| // Name as stored in the tracking table — the directory name for directory- | ||
| // style migrations, or the filename with `.sql` stripped for flat files. | ||
| name: string | ||
| // Absolute path on disk (directory or file). | ||
| path: string | ||
| } | ||
|
|
||
| export const migrationsReset = async (options: MigrationsResetOptions, command: BaseCommand) => { | ||
| const branch = options.branch ?? process.env.NETLIFY_DB_BRANCH | ||
| const json = options.json ?? false | ||
|
|
||
| if (branch) { | ||
| await resetAgainstBranch(branch, json, command) | ||
| return | ||
| } | ||
|
|
||
| await resetAgainstLocal(json, command) | ||
| } | ||
|
|
||
| const resetAgainstLocal = async (json: boolean, command: BaseCommand): Promise<void> => { | ||
| const buildDir = command.netlify.site.root ?? command.project.root ?? command.project.baseDirectory | ||
| if (!buildDir) { | ||
| throw new Error('Could not determine the project root directory.') | ||
| } | ||
|
|
||
| const migrationsDirectory = resolveMigrationsDirectory(command) | ||
|
|
||
| if (!json) { | ||
| log('Removing local migration files that have not been applied to the local development database.') | ||
| } | ||
|
|
||
| const { executor, cleanup } = await connectToDatabase(buildDir) | ||
|
|
||
| let deleted: string[] | ||
| try { | ||
| const applied = await localAppliedMigrations({ executor })() | ||
| const appliedNames = new Set(applied.map((m) => m.name)) | ||
| deleted = await deletePendingMigrationFiles(migrationsDirectory, appliedNames) | ||
| } finally { | ||
| await cleanup() | ||
| } | ||
|
|
||
| logOutcome(deleted, { json, target: 'local' }) | ||
| } | ||
|
|
||
| const resetAgainstBranch = async (branch: string, json: boolean, command: BaseCommand): Promise<void> => { | ||
| const siteId = command.siteId | ||
| const accessToken = command.netlify.api.accessToken | ||
| const basePath = command.netlify.api.basePath | ||
|
|
||
| if (!siteId) { | ||
| throw new Error(`The project must be linked with ${netlifyCommand()} link to target a remote branch.`) | ||
| } | ||
| if (!accessToken) { | ||
| throw new Error(`You must be logged in with ${netlifyCommand()} login to target a remote branch.`) | ||
| } | ||
|
|
||
| const migrationsDirectory = resolveMigrationsDirectory(command) | ||
|
|
||
| if (!json) { | ||
| log( | ||
| `Removing local migration files that have not been applied to database branch ${chalk.bold(branch)}. ` + | ||
| 'Files that are already applied to the branch are kept untouched.', | ||
| ) | ||
| } | ||
|
|
||
| const applied = await remoteAppliedMigrations({ siteId, accessToken, basePath, branch })() | ||
| const appliedNames = new Set(applied.map((m) => m.name)) | ||
|
|
||
| const deleted = await deletePendingMigrationFiles(migrationsDirectory, appliedNames) | ||
|
|
||
| logOutcome(deleted, { json, target: 'branch', branch }) | ||
| } | ||
|
|
||
| const logOutcome = ( | ||
| deleted: string[], | ||
| params: { json: boolean; target: 'local' | 'branch'; branch?: string }, | ||
| ): void => { | ||
| if (params.json) { | ||
| logJson({ | ||
| reset: true, | ||
| target: params.target, | ||
| ...(params.branch ? { branch: params.branch } : {}), | ||
| pendingMigrationFilesDeleted: deleted, | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| if (deleted.length === 0) { | ||
| log('No pending migration files to delete — all local migrations are already applied.') | ||
| return | ||
| } | ||
| log(`Deleted ${String(deleted.length)} pending migration file(s):`) | ||
| for (const name of deleted) { | ||
| log(` • ${name}`) | ||
| } | ||
| } | ||
|
|
||
| const deletePendingMigrationFiles = async ( | ||
| migrationsDirectory: string, | ||
| appliedNames: Set<string>, | ||
| ): Promise<string[]> => { | ||
| const local = await readLocalMigrations(migrationsDirectory) | ||
| const pending = local.filter((m) => !appliedNames.has(m.name)) | ||
| for (const migration of pending) { | ||
| await rm(migration.path, { recursive: true, force: true }) | ||
| } | ||
| return pending.map((m) => m.name) | ||
| } | ||
|
|
||
| const readLocalMigrations = async (migrationsDirectory: string): Promise<LocalMigration[]> => { | ||
| let entries | ||
| try { | ||
| entries = await readdir(migrationsDirectory, { withFileTypes: true }) | ||
| } catch (error) { | ||
| if ((error as NodeJS.ErrnoException).code === 'ENOENT') { | ||
| return [] | ||
| } | ||
| throw error | ||
| } | ||
|
|
||
| const migrations: LocalMigration[] = [] | ||
| for (const entry of entries) { | ||
| const entryPath = join(migrationsDirectory, entry.name) | ||
| if (entry.isDirectory()) { | ||
| migrations.push({ name: entry.name, path: entryPath }) | ||
| } else if (entry.isFile() && entry.name.endsWith(SQL_EXTENSION)) { | ||
| migrations.push({ name: entry.name.slice(0, -SQL_EXTENSION.length), path: entryPath }) | ||
| } | ||
| } | ||
| return migrations | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,3 @@ | ||
| export const MIGRATIONS_SCHEMA = 'netlify' | ||
| export const MIGRATIONS_TABLE = `${MIGRATIONS_SCHEMA}.migrations` | ||
| export const PRODUCTION_BRANCH = 'production' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't exactly suggest this (I'm struggling on exact wording) - but just to sync with the removal of the production branch check removal.
Can be done in follow up
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
looking at command like
migrations pull- it also seem like you can do just--branchthere (and it would useproduction) and maybe some wording for handling those cases can be borrowed here