-
Notifications
You must be signed in to change notification settings - Fork 445
feat: add db migrate command
#7985
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
+272
−7
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
2c42866
feat: add `db migrate` command
eduardoboucas 756f774
chore: format
eduardoboucas dfb5a65
chore: lint
eduardoboucas 4b4af99
Merge branch 'main' into feat/db-migrate
eduardoboucas bdb6fca
fix: fix type
eduardoboucas 1cdcc07
use db instance from dev
paulo ef592e9
Merge branch 'main' into feat/db-migrate
paulo 5e830f9
Update src/commands/database/migrate.ts
paulo ecd6554
minor fix
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
Some comments aren't visible on the classic Files Changed page.
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,63 @@ | ||
| import { NetlifyDev } from '@netlify/dev' | ||
|
|
||
| import { log, logJson } from '../../utils/command-helpers.js' | ||
| import BaseCommand from '../base-command.js' | ||
|
|
||
| export interface MigrateOptions { | ||
| to?: string | ||
| json?: boolean | ||
| } | ||
|
|
||
| export const migrate = async (options: MigrateOptions, command: BaseCommand) => { | ||
| const { to: name, json } = options | ||
| 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 = command.netlify.config.db?.migrations?.path | ||
| if (!migrationsDirectory) { | ||
| throw new Error( | ||
| 'No migrations directory found. Create a directory at netlify/db/migrations or set `db.migrations.path` in `netlify.toml`.', | ||
| ) | ||
| } | ||
|
|
||
| const netlifyDev = new NetlifyDev({ | ||
| projectRoot: buildDir, | ||
| aiGateway: { enabled: false }, | ||
| blobs: { enabled: false }, | ||
| edgeFunctions: { enabled: false }, | ||
| environmentVariables: { enabled: false }, | ||
| functions: { enabled: false }, | ||
| geolocation: { enabled: false }, | ||
| headers: { enabled: false }, | ||
| images: { enabled: false }, | ||
| redirects: { enabled: false }, | ||
| staticFiles: { enabled: false }, | ||
| serverAddress: null, | ||
| }) | ||
|
|
||
| try { | ||
| await netlifyDev.start() | ||
|
|
||
| const { db } = netlifyDev | ||
| if (!db) { | ||
| throw new Error('Local database failed to start. Set EXPERIMENTAL_NETLIFY_DB_ENABLED=1 to enable.') | ||
| } | ||
|
|
||
| const applied = await db.applyMigrations(migrationsDirectory, name) | ||
|
|
||
| if (json) { | ||
| logJson({ migrations_applied: applied }) | ||
| } else if (applied.length === 0) { | ||
| log('No pending migrations to apply.') | ||
| } else { | ||
| log(`Applied ${String(applied.length)} migration${applied.length === 1 ? '' : 's'}:`) | ||
| for (const migration of applied) { | ||
| log(` - ${migration}`) | ||
| } | ||
| } | ||
| } finally { | ||
| await netlifyDev.stop() | ||
| } | ||
| } | ||
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,180 @@ | ||
| import { describe, expect, test, vi, beforeEach } from 'vitest' | ||
|
|
||
| const { mockStart, mockStop, mockApplyMigrations, MockNetlifyDev, logMessages, jsonMessages } = vi.hoisted(() => { | ||
| const mockStart = vi.fn().mockResolvedValue({}) | ||
| const mockStop = vi.fn().mockResolvedValue(undefined) | ||
| const mockApplyMigrations = vi.fn().mockResolvedValue([]) | ||
| const MockNetlifyDev = vi.fn().mockImplementation(() => ({ | ||
| start: mockStart, | ||
| stop: mockStop, | ||
| db: { applyMigrations: mockApplyMigrations }, | ||
| })) | ||
| const logMessages: string[] = [] | ||
| const jsonMessages: unknown[] = [] | ||
| return { mockStart, mockStop, mockApplyMigrations, MockNetlifyDev, logMessages, jsonMessages } | ||
| }) | ||
|
|
||
| vi.mock('@netlify/dev', () => ({ | ||
| NetlifyDev: MockNetlifyDev, | ||
| })) | ||
|
|
||
| vi.mock('../../../../src/utils/command-helpers.js', async () => ({ | ||
| ...(await vi.importActual('../../../../src/utils/command-helpers.js')), | ||
| log: (...args: string[]) => { | ||
| logMessages.push(args.join(' ')) | ||
| }, | ||
| logJson: (message: unknown) => { | ||
| jsonMessages.push(message) | ||
| }, | ||
| })) | ||
|
|
||
| import { migrate } from '../../../../src/commands/database/migrate.js' | ||
|
|
||
| function createMockCommand(overrides: { buildDir?: string; projectRoot?: string; migrationsPath?: string } = {}) { | ||
| const { | ||
| buildDir = '/project', | ||
| projectRoot = '/project', | ||
| migrationsPath = '/project/netlify/db/migrations', | ||
| } = overrides | ||
|
|
||
| return { | ||
| project: { root: projectRoot, baseDirectory: undefined }, | ||
| netlify: { | ||
| site: { root: buildDir }, | ||
| config: { db: { migrations: { path: migrationsPath } } }, | ||
| }, | ||
| } as unknown as Parameters<typeof migrate>[1] | ||
| } | ||
|
|
||
| describe('migrate', () => { | ||
| beforeEach(() => { | ||
| logMessages.length = 0 | ||
| jsonMessages.length = 0 | ||
| vi.clearAllMocks() | ||
| mockApplyMigrations.mockResolvedValue([]) | ||
| }) | ||
|
|
||
| test('creates NetlifyDev with the correct project root and all non-db features disabled', async () => { | ||
| await migrate({}, createMockCommand({ buildDir: '/my/project' })) | ||
|
|
||
| expect(MockNetlifyDev).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| projectRoot: '/my/project', | ||
| aiGateway: { enabled: false }, | ||
| blobs: { enabled: false }, | ||
| edgeFunctions: { enabled: false }, | ||
| environmentVariables: { enabled: false }, | ||
| functions: { enabled: false }, | ||
| geolocation: { enabled: false }, | ||
| headers: { enabled: false }, | ||
| images: { enabled: false }, | ||
| redirects: { enabled: false }, | ||
| staticFiles: { enabled: false }, | ||
| serverAddress: null, | ||
| }), | ||
| ) | ||
| }) | ||
|
|
||
| test('starts and stops NetlifyDev', async () => { | ||
| await migrate({}, createMockCommand()) | ||
|
|
||
| expect(mockStart).toHaveBeenCalledOnce() | ||
| expect(mockStop).toHaveBeenCalledOnce() | ||
| }) | ||
|
|
||
| test('stops NetlifyDev even when applyMigrations throws', async () => { | ||
| mockApplyMigrations.mockRejectedValueOnce(new Error('migration failed')) | ||
|
|
||
| await expect(migrate({}, createMockCommand())).rejects.toThrow('migration failed') | ||
|
|
||
| expect(mockStop).toHaveBeenCalledOnce() | ||
| }) | ||
|
|
||
| test('throws when db is not available after start', async () => { | ||
| MockNetlifyDev.mockImplementationOnce(() => ({ | ||
| start: mockStart, | ||
| stop: mockStop, | ||
| db: undefined, | ||
| })) | ||
|
|
||
| await expect(migrate({}, createMockCommand())).rejects.toThrow('Local database failed to start') | ||
| }) | ||
|
|
||
| test('uses migrations directory from config', async () => { | ||
| await migrate({}, createMockCommand({ migrationsPath: '/custom/migrations' })) | ||
|
|
||
| expect(mockApplyMigrations).toHaveBeenCalledWith('/custom/migrations', undefined) | ||
| }) | ||
|
|
||
| test('throws when no migrations directory is configured', async () => { | ||
| const command = { | ||
| project: { root: '/project', baseDirectory: undefined }, | ||
| netlify: { site: { root: '/project' }, config: {} }, | ||
| } as unknown as Parameters<typeof migrate>[1] | ||
|
|
||
| await expect(migrate({}, command)).rejects.toThrow('No migrations directory found') | ||
| }) | ||
|
|
||
| test('passes the --to target to applyMigrations', async () => { | ||
| await migrate({ to: '0002_add_posts' }, createMockCommand()) | ||
|
|
||
| expect(mockApplyMigrations).toHaveBeenCalledWith(expect.any(String), '0002_add_posts') | ||
| }) | ||
|
|
||
| test('logs message when no migrations are applied', async () => { | ||
| mockApplyMigrations.mockResolvedValueOnce([]) | ||
|
|
||
| await migrate({}, createMockCommand()) | ||
|
|
||
| expect(logMessages).toContain('No pending migrations to apply.') | ||
| }) | ||
|
|
||
| test('logs each applied migration', async () => { | ||
| mockApplyMigrations.mockResolvedValueOnce(['0001_create_users', '0002_add_posts']) | ||
|
|
||
| await migrate({}, createMockCommand()) | ||
|
|
||
| expect(logMessages[0]).toContain('2 migrations') | ||
| expect(logMessages).toContain(' - 0001_create_users') | ||
| expect(logMessages).toContain(' - 0002_add_posts') | ||
| }) | ||
|
|
||
| test('uses singular "migration" when only one is applied', async () => { | ||
| mockApplyMigrations.mockResolvedValueOnce(['0001_create_users']) | ||
|
|
||
| await migrate({}, createMockCommand()) | ||
|
|
||
| expect(logMessages[0]).toMatch(/1 migration:$/) | ||
| }) | ||
|
|
||
| test('outputs JSON when --json flag is set', async () => { | ||
| mockApplyMigrations.mockResolvedValueOnce(['0001_create_users', '0002_add_posts']) | ||
|
|
||
| await migrate({ json: true }, createMockCommand()) | ||
|
|
||
| expect(jsonMessages).toHaveLength(1) | ||
| expect(jsonMessages[0]).toEqual({ | ||
| migrations_applied: ['0001_create_users', '0002_add_posts'], | ||
| }) | ||
| }) | ||
|
|
||
| test('outputs empty migrations_applied array in JSON mode when none applied', async () => { | ||
| mockApplyMigrations.mockResolvedValueOnce([]) | ||
|
|
||
| await migrate({ json: true }, createMockCommand()) | ||
|
|
||
| expect(jsonMessages).toHaveLength(1) | ||
| expect(jsonMessages[0]).toEqual({ | ||
| migrations_applied: [], | ||
| }) | ||
| }) | ||
|
|
||
| test('throws when project root cannot be determined', async () => { | ||
| const command = { | ||
| project: { root: undefined, baseDirectory: undefined }, | ||
| netlify: { site: { root: undefined }, config: {} }, | ||
| } as unknown as Parameters<typeof migrate>[1] | ||
|
|
||
| await expect(migrate({}, command)).rejects.toThrow('Could not determine the project root directory.') | ||
| }) | ||
| }) |
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.