-
Notifications
You must be signed in to change notification settings - Fork 447
feat: scaffold migration command #8022
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
+463
−6
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
182fe9e
feat: scaffold migration command
paulo 6eb5333
address the rabbit
paulo d7e692c
Merge branch 'main' into pa/migration-new-command
paulo 4b00915
dedup code
paulo 05a97d8
add better example
paulo ec6a65d
lint
paulo 426af3d
fix the rabbit
paulo 2d9cb32
Merge branch 'main' into pa/migration-new-command
paulo 226fc7b
lint again...
paulo 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,170 @@ | ||
| import { readdir, mkdir, writeFile } from 'fs/promises' | ||
| import { join } from 'path' | ||
|
|
||
| import inquirer from 'inquirer' | ||
|
|
||
| import { log, logJson } from '../../utils/command-helpers.js' | ||
| import BaseCommand from '../base-command.js' | ||
|
|
||
| export type NumberingScheme = 'sequential' | 'timestamp' | ||
|
|
||
| export interface MigrationNewOptions { | ||
| description?: string | ||
| scheme?: NumberingScheme | ||
| json?: boolean | ||
| } | ||
|
|
||
| export const generateSlug = (description: string): string => { | ||
| return description | ||
| .toLowerCase() | ||
| .trim() | ||
| .replace(/[^a-z0-9\s_-]/g, '') | ||
| .replace(/[\s_]+/g, '-') | ||
| .replace(/-+/g, '-') | ||
| .replace(/^-|-$/g, '') | ||
| } | ||
|
|
||
| export const detectNumberingScheme = (existingNames: string[]): NumberingScheme | undefined => { | ||
| if (existingNames.length === 0) { | ||
| return undefined | ||
| } | ||
|
|
||
| const prefixes = existingNames.map((name) => name.split(/[_-]/)[0]) | ||
| const allTimestamp = prefixes.every((p) => /^\d{14}$/.test(p)) | ||
| if (allTimestamp) { | ||
| return 'timestamp' | ||
| } | ||
|
|
||
| const allSequential = prefixes.every((p) => /^\d{4}$/.test(p)) | ||
| if (allSequential) { | ||
| return 'sequential' | ||
| } | ||
|
|
||
| return undefined | ||
| } | ||
|
|
||
| export const generateNextPrefix = (existingNames: string[], scheme: NumberingScheme): string => { | ||
| if (scheme === 'timestamp') { | ||
| const now = new Date() | ||
| const pad = (n: number, width = 2) => String(n).padStart(width, '0') | ||
| return [ | ||
| now.getFullYear(), | ||
| pad(now.getMonth() + 1), | ||
| pad(now.getDate()), | ||
| pad(now.getHours()), | ||
| pad(now.getMinutes()), | ||
| pad(now.getSeconds()), | ||
| ].join('') | ||
| } | ||
|
|
||
| const prefixes = existingNames.map((name) => { | ||
| const match = /^(\d{4})[_-]/.exec(name) | ||
| return match ? parseInt(match[1], 10) : 0 | ||
| }) | ||
| const maxPrefix = prefixes.length > 0 ? Math.max(...prefixes) : 0 | ||
| return String(maxPrefix + 1).padStart(4, '0') | ||
| } | ||
|
|
||
| const getExistingMigrationNames = async (migrationsDirectory: string): Promise<string[]> => { | ||
| try { | ||
| const entries = await readdir(migrationsDirectory, { withFileTypes: true }) | ||
| return entries | ||
| .filter((entry) => entry.isDirectory()) | ||
| .map((entry) => entry.name) | ||
| .sort() | ||
| } catch (error) { | ||
| if ((error as NodeJS.ErrnoException).code === 'ENOENT') { | ||
| return [] | ||
| } | ||
| throw error | ||
| } | ||
| } | ||
|
|
||
| const DEFAULT_MIGRATIONS_PATH = 'netlify/db/migrations' | ||
|
|
||
| export const resolveMigrationsDirectory = (command: BaseCommand): string => { | ||
| const configuredPath = command.netlify.config.db?.migrations?.path | ||
| if (configuredPath) { | ||
| return configuredPath | ||
| } | ||
|
|
||
| const projectRoot = command.netlify.site.root ?? command.project.root ?? command.project.baseDirectory | ||
| if (!projectRoot) { | ||
| throw new Error('Could not determine the project root directory.') | ||
| } | ||
|
|
||
| return join(projectRoot, DEFAULT_MIGRATIONS_PATH) | ||
| } | ||
|
|
||
| export const migrationNew = async (options: MigrationNewOptions, command: BaseCommand) => { | ||
| const { json } = options | ||
|
|
||
| const migrationsDirectory = resolveMigrationsDirectory(command) | ||
| const existingMigrations = await getExistingMigrationNames(migrationsDirectory) | ||
| const detectedScheme = detectNumberingScheme(existingMigrations) | ||
|
|
||
| let description = options.description | ||
| let scheme = options.scheme | ||
|
|
||
| if (!description) { | ||
| const answers = await inquirer.prompt<{ description: string }>([ | ||
| { | ||
| type: 'input', | ||
| name: 'description', | ||
| message: 'What is the purpose of this migration?', | ||
| validate: (input: string) => (input.trim().length > 0 ? true : 'Description cannot be empty'), | ||
| }, | ||
| ]) | ||
| description = answers.description | ||
| } | ||
|
|
||
| if (!scheme) { | ||
| const answers = await inquirer.prompt<{ scheme: NumberingScheme }>([ | ||
| { | ||
| type: 'list', | ||
| name: 'scheme', | ||
| message: 'Numbering scheme:', | ||
| choices: [ | ||
| { name: 'Sequential (0001, 0002, ...)', value: 'sequential' }, | ||
| { name: 'Timestamp (20260312143000)', value: 'timestamp' }, | ||
| ], | ||
| ...(detectedScheme && { default: detectedScheme }), | ||
| }, | ||
| ]) | ||
| scheme = answers.scheme | ||
| } | ||
|
|
||
| const slug = generateSlug(description) | ||
| if (!slug) { | ||
| throw new Error( | ||
| `Description "${description}" produces an empty slug. Use a description with alphanumeric characters (e.g. "add users table").`, | ||
| ) | ||
| } | ||
|
|
||
| const prefix = generateNextPrefix(existingMigrations, scheme) | ||
| const folderName = `${prefix}_${slug}` | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const folderPath = join(migrationsDirectory, folderName) | ||
| const migrationFilePath = join(folderPath, 'migration.sql') | ||
|
|
||
| await mkdir(folderPath, { recursive: true }) | ||
| await writeFile( | ||
| migrationFilePath, | ||
| `-- Write your migration SQL here | ||
| -- | ||
| -- Example: | ||
| -- CREATE TABLE IF NOT EXISTS users ( | ||
| -- id SERIAL PRIMARY KEY, | ||
| -- name TEXT NOT NULL, | ||
| -- created_at TIMESTAMP DEFAULT NOW() | ||
| -- ); | ||
| `, | ||
| { flag: 'wx' }, | ||
| ) | ||
|
|
||
| if (json) { | ||
| logJson({ path: folderPath, name: folderName }) | ||
| } else { | ||
| log(`Created migration: ${folderName}`) | ||
| log(` ${join(folderPath, 'migration.sql')}`) | ||
| } | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.