Skip to content

feat: Add rebase migration command - #4515

Open
jwelmac wants to merge 84 commits into
serverpod:mainfrom
Khuwn-Soulutions:feature/rebase-migration-command
Open

jwelmac wants to merge 84 commits into
serverpod:mainfrom
Khuwn-Soulutions:feature/rebase-migration-command

Conversation

@jwelmac

@jwelmac jwelmac commented Dec 29, 2025 •

Copy link
Copy Markdown
Contributor

This PR implements a rebase-migration command that removes all migrations created after a base migration and creates a new one to correctly append to the history.

Fixes #4503

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added rebase-migration CLI command to consolidate migrations with options for specifying base migration (--onto), check mode (--check), force flag (--force), and tagging (--tag).
    • Updated migration creation to return migration names for improved tracking.
  • Tests

    • Added comprehensive end-to-end test suite for migration rebase scenarios.
    • Added shared test utilities for logging and analytics mocking.

✏️ Tip: You can customize this high-level summary in your review settings.

- the migration id can be passed in during CI
@jwelmac
jwelmac marked this pull request as draft December 29, 2025 01:12
@jwelmac jwelmac changed the title Feature/rebase migration command feat: add rebase migration command Dec 29, 2025
@jwelmac
jwelmac marked this pull request as ready for review January 1, 2026 23:25
@jwelmac

jwelmac commented Jan 2, 2026

Copy link
Copy Markdown
Contributor Author

@SandPod @marcelomendoncasoares @coderabbitai
This PR completes all requirements for #4503.
Since the rebase-migration command runs the create-migration command under the hood it takes the same options.

One thing I would like some help/insight on are the e2e tests.
I realized there are a lot of locations that I could do the test in and a lot of different scaffolding for these types of tests. 😓
I chose at first the most logical location (tests/serverpod_cli_e2e/test/rebase_migration_test.dart), but I hit a wall in that the database is not reset between tests and as such the tests after the first 3 started failing.
Instead of twisting myself into a knot to get it working I thought it best to stop and ask for recommendations.

Overall the new command works superbly I just would like to see the e2e/integration tests work for all permutations to have that peace that it is stable and reliable.

@coderabbitai

coderabbitai Bot commented Jan 2, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the rebase_migration_test.dart file
cat tests/serverpod_cli_e2e/test/rebase_migration_test.dart

Length of output: 87


🏁 Script executed:

#!/bin/bash
# List all test files in the serverpod_cli_e2e directory to understand the structure
fd -e dart . tests/serverpod_cli_e2e/test/

Length of output: 116


🏁 Script executed:

#!/bin/bash
# Look at similar migration test files for patterns
cat tests/serverpod_cli_e2e/test/create_migration_test.dart

Length of output: 87


🏁 Script executed:

#!/bin/bash
# Check for any test helper files or setup utilities
fd -e dart . tests/serverpod_cli_e2e/test/ --exec grep -l "setUp\|tearDown" {} \;

Length of output: 116


🏁 Script executed:

#!/bin/bash
# Look for database setup patterns in the test directory
rg -n "setUp|tearDown|resetDatabase|dropDatabase" tests/serverpod_cli_e2e/test/ -A 3

Length of output: 69


🏁 Script executed:

#!/bin/bash
# Find the serverpod_cli_e2e directory
fd -t d "serverpod_cli_e2e"

Length of output: 78


🏁 Script executed:

#!/bin/bash
# Search for rebase_migration_test.dart
fd "rebase_migration_test.dart"

Length of output: 121


🏁 Script executed:

#!/bin/bash
# Look for any test directories
fd -t d "test" | head -20

Length of output: 1350


🏁 Script executed:

#!/bin/bash
# Use gh to get the PR diff to see the file structure
gh pr view 4515 --json files --jq '.files[].path' | grep -i test | head -20

Length of output: 766


🏁 Script executed:

#!/bin/bash
# Read the rebase_migration_test.dart file
cat tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart

Length of output: 19607


🏁 Script executed:

#!/bin/bash
# List all test files in the serverpod_cli_e2e_test directory
fd -e dart . tests/serverpod_cli_e2e_test/test/ | head -20

Length of output: 526


🏁 Script executed:

#!/bin/bash
# Look at other migration-related test files for patterns
cat tests/serverpod_cli_e2e_test/test/create_migration_test.dart 2>/dev/null || echo "File not found"

Length of output: 14


🏁 Script executed:

#!/bin/bash
# Search for database setup/teardown patterns in e2e tests
rg -n "setUp|tearDown|resetDatabase|dropDatabase|@Tags" tests/serverpod_cli_e2e_test/test/ -C 2 | head -50

Length of output: 4049


🏁 Script executed:

#!/bin/bash
# Look at the create_migration_exit_code_test.dart for comparison
cat tests/serverpod_cli_e2e_test/test/create_migration_exit_code_test.dart

Length of output: 4221


🏁 Script executed:

#!/bin/bash
# Check if there are any test utilities or helpers
fd -e dart . tests/serverpod_cli_e2e_test/src/ tests/serverpod_cli_e2e_test/lib/

Length of output: 326


🏁 Script executed:

#!/bin/bash
# Look for any database reset or cleanup patterns in the codebase
rg -n "cleanUp|cleanup|reset.*database|drop.*database|deleteProject" tests/serverpod_cli_e2e_test/ -A 3 | head -40

Length of output: 785


🏁 Script executed:

#!/bin/bash
# Check the run_serverpod utility to understand how it works
cat tests/serverpod_cli_e2e_test/lib/src/run_serverpod.dart

Length of output: 3683


🏁 Script executed:

#!/bin/bash
# Look for database connection patterns in e2e tests
rg -n "PostgreSQL|docker|database.*connect|Database\(" tests/serverpod_cli_e2e_test/ -C 2 | head -50

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Check the shared_test_dir.dart to understand test isolation
cat tests/serverpod_cli_e2e_test/lib/src/shared_test_dir.dart

Length of output: 1596


🏁 Script executed:

#!/bin/bash
# Look for how migration tests handle database state in the main serverpod tests
fd -e dart migration tests/ | grep -E "(integration|e2e)" | head -10

Length of output: 881


🏁 Script executed:

#!/bin/bash
# Check if there are any test setup files or configuration
cat tests/serverpod_cli_e2e_test/dart_test.yaml 2>/dev/null || echo "No dart_test.yaml found"

Length of output: 168


🏁 Script executed:

#!/bin/bash
# Look at the unit test for rebase_migration to understand the approach
cat tools/serverpod_cli/test/commands/rebase_migration_test.dart

Length of output: 6237


🏁 Script executed:

#!/bin/bash
# Look at how serverpod_test_server handles migration e2e tests with database
cat tests/serverpod_test_server/test_e2e_migrations/apply_repair_migration_test.dart | head -100

Length of output: 2820


🏁 Script executed:

#!/bin/bash
# Check if there's a test helper or setup for database tests
rg -n "withServerpod|IntegrationTestSession|TestSession" tests/serverpod_test_server/test_e2e_migrations/ -A 2 | head -50

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Look at the structure of migration tests in serverpod_test_server
fd -t f . tests/serverpod_test_server/test_e2e_migrations/ | head -15

Length of output: 1024


🏁 Script executed:

#!/bin/bash
# Check if there are README or documentation files about testing
cat tests/serverpod_cli_e2e_test/README.md 2>/dev/null || cat tests/serverpod_test_server/README.md 2>/dev/null || echo "No README found"

Length of output: 408


🏁 Script executed:

#!/bin/bash
# Look at the MigrationTestUtils to understand how they handle database state
cat tests/serverpod_test_server/test_util/migration_test_utils.dart

Length of output: 95


🏁 Script executed:

#!/bin/bash
# Check how many tests are currently being skipped in rebase_migration_test
rg -n "skip:" tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart

Length of output: 43


🏁 Script executed:

#!/bin/bash
# Look at another e2e test that might create projects to see patterns
cat tests/serverpod_cli_e2e_test/test/create_migration_from_anywhere_test.dart

Length of output: 4880


@jwelmac Thank you for the detailed context! I've analyzed your test file and compared it with other e2e tests in the codebase. Here are my recommendations:

Analysis of the Issue

Looking at your rebase_migration_test.dart, I can see that:

  1. Good news: Your test structure already creates a unique project per test via setUp(), so file system isolation should be working correctly
  2. The skipped tests: Two test groups are marked with skip: true (lines 496 and 626) - these are the ones likely causing issues

Key Differences in Test Approaches

The Serverpod codebase uses two different testing strategies:

1. File-based tests (your current approach - serverpod_cli_e2e_test)

  • Create temporary projects with unique names
  • Test CLI commands and file system operations
  • No actual database connection
  • Examples: create_migration_exit_code_test.dart, create_migration_from_anywhere_test.dart

2. Database-backed tests (serverpod_test_server/test_e2e_migrations)

  • Connect to a real database
  • Use MigrationTestUtils.migrationTestCleanup() for teardown
  • Test actual database schema changes
  • Examples: apply_repair_migration_test.dart

Recommendations

Option 1: Keep File-Based Tests Isolated (Recommended for your current approach)

Since your tests don't actually need a database connection (they test CLI behavior and file operations), ensure complete isolation:

setUp(() async {
  await createProject();
  // Ensure we're starting fresh - could add explicit cleanup here if needed
});

tearDown(() async {
  // Optional: Explicitly delete the project directory after each test
  if (Directory(serverDir).existsSync()) {
    Directory(serverDir).parent.deleteSync(recursive: true);
  }
});

Option 2: Fix the Skipped Tests

The skipped test groups have complex scenarios that might need refinement:

For "Given a conflict in registry" tests:

  • These tests manually edit the registry file to simulate merge conflicts
  • They should work without a database since they're just manipulating files
  • Try running them individually first to isolate the failure

For "Given destructive changes" tests:

  • These test --force flag behavior with schema-breaking changes
  • Again, should work without database since it's testing CLI behavior

Specific Fix for Skipped TestsTry approaching the skipped tests with better isolation strategy:

Suggested Approach: Group-Level Setup

Try using setUpAll and tearDownAll for the skipped test groups to create a single project for all tests within that group:

group(
  'Given a conflict in registry',
  () {
    late String projectName;
    late String serverDir;
    late Directory migrationsDir;
    late List<String> previousMigrations;

    setUpAll(() async {
      projectName = 'test_${const Uuid().v4().replaceAll('-', '_').toLowerCase()}';
      var result = await runServerpod(
        ['create', projectName],
        workingDirectory: d.sandbox,
      );
      expect(result.exitCode, 0, reason: 'Failed to create project: ${result.stderr}');
      
      serverDir = path.join(d.sandbox, projectName, '${projectName}_server');
      migrationsDir = Directory(path.join(serverDir, 'migrations'));
      previousMigrations = getMigrationNames();
    });

    tearDownAll(() async {
      // Clean up the project
      final projectDir = Directory(path.join(d.sandbox, projectName));
      if (projectDir.existsSync()) {
        projectDir.deleteSync(recursive: true);
      }
    });

    test('when rebasing then rebase onto the incoming migration', () async {
      // Test implementation here - can now use shared serverDir
      // ...
    });

    // More tests in the group...
  },
);

Alternative: Run Tests Sequentially

Add to your dart_test.yaml:

timeout: 3x
concurrency: 1  # Run tests one at a time

This ensures no concurrent state issues but will be slower.

Debugging Strategy

  1. Run tests individually to see which one truly fails:

    dart test tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart --name "when rebasing then rebase onto the incoming migration"
  2. Add debug output to track state:

    test('...', () async {
      print('DEBUG: Migrations before test: ${getMigrationNames()}');
      // ... test code
      print('DEBUG: Migrations after test: ${getMigrationNames()}');
    });
  3. Check for leftover state - The issue might be that the d.sandbox directory contains artifacts from previous test runs. Ensure the sandbox is cleaned between test file executions.

Why the Tests Might Be Failing

Looking at your skipped tests:

  • They manipulate the migration registry file directly
  • They simulate "incoming" migrations by copying files
  • They test conflict resolution scenarios

These don't actually need a database - they're testing file operations and CLI behavior. The failures might be due to:

  1. Timing issues (migrations need unique timestamps)
  2. Registry file state persisting unexpectedly
  3. The previousMigrations baseline being calculated at the wrong time

Recommendation for Next Steps

  1. Start with one skipped test - Remove skip: true from just the first test in "Given a conflict in registry"
  2. Add logging to see exactly what's happening with the migration state
  3. Check if unique project creation is actually working - print the project path
  4. Consider whether these tests would benefit from being in separate test files for better isolation

Would you like me to help you debug a specific test or create a minimal reproduction case to isolate the issue?


🧠 Learnings used
Learnt from: CR
Repo: serverpod/serverpod PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-11T03:56:54.151Z
Learning: Verify example projects still work before submitting PR by running example servers with 'dart bin/main.dart --apply-migrations'

@jwelmac

jwelmac commented Jan 2, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jan 2, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jan 2, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces a new rebase-migration CLI command to automate consolidation of conflicting migrations when multiple developers' feature branches merge. The implementation includes the command handler, runner interface, comprehensive e2e tests covering multiple scenarios, unit tests with mocks, and refactored shared test utilities.

Changes

Cohort / File(s) Summary
Rebase Migration Command
tools/serverpod_cli/lib/src/commands/rebase_migration.dart
New command class with RebaseMigrationOption enum; implements runWithConfig for argument parsing (onto, check, force, tag), environment validation, and delegating to RebaseMigrationRunner; includes testing hook for dependency injection via optional rebaseMigrationRunner field.
CLI Command Registration
tools/serverpod_cli/bin/serverpod_cli.dart
Imports and registers RebaseMigrationCommand in the command runner's initialization.
Create Migration Command Refactoring
tools/serverpod_cli/lib/src/commands/create_migration.dart
Extracts migration logic into new CreateMigrationRunner class; command now delegates to runner.run; createMigration method returns String? (migration name on success, null if no changes) instead of void; adds detailed error handling and inline documentation.
Command Unit Tests
tools/serverpod_cli/test/commands/rebase_migration_test.dart
Tests RebaseMigrationCommand with MockRebaseMigrationRunner; covers error paths (empty --onto, missing config, disabled database feature) and success paths (check mode vs rebase mode).
Shared Test Utilities
tools/serverpod_cli/test/test_util/mock_log.dart
New shared test utility with MockLogOutput, MockLogger (extends VoidLogger), and MockAnalytics implementations for logging and event tracking.
Command Runner Test Refactoring
tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
Replaces in-file logging/analytics mocks with import from shared mock_log; introduces TestFixture container and createTestFixture factory; adds MockCommand, LanguageServerMockCommand, and MockVersionCommand test helpers.
E2E Test Suite
tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
Comprehensive end-to-end tests for rebase-migration behavior; covers rebase onto specified base (with/without tags), rebase onto intermediate migrations, check mode validation, conflict resolution with incoming migrations, multiple incoming migrations, and destructive change handling (with --force). Includes helper utilities: writeModel, createMigration, rebaseMigration, getMigrationNames, copyIncomingMigration.
E2E Test Fixtures
tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/{definition.json, definition.sql, definition_project.json, migration.json, migration.sql}
Test data defining a complete incoming migration with DatabaseDefinition, SQL schema bootstrap (plpgsql UUID v7 generator function, core/auth/logging tables, indexes, foreign keys), project-level table definitions, and migration entries.

Sequence Diagram(s)

sequenceDiagram
    participant User as Developer
    participant Cmd as RebaseMigrationCommand
    participant Val as Environment Validator
    participant Cfg as GeneratorConfig
    participant Runner as RebaseMigrationRunner
    participant Gen as MigrationGenerator
    participant Reg as Migration Registry

    User->>Cmd: rebase-migration --onto [base] [--check] [--force]
    Cmd->>Cmd: Parse onto, check, force, tag arguments
    Cmd->>Val: _validateCommandEnvironment()
    Val->>Cfg: Load GeneratorConfig (interactive)
    Val->>Cfg: Verify database feature enabled
    Cfg-->>Val: Config loaded
    Val-->>Cmd: Validated GeneratorConfig
    
    alt Check Mode
        Cmd->>Runner: checkMigration(onto, config)
        Runner->>Gen: Validate migration state
        Gen->>Reg: Query migration history
        Reg-->>Gen: Conflicts/status
        Gen-->>Runner: Check result
        Runner-->>Cmd: Status (exit code, messages)
        Cmd-->>User: Display check results
    else Rebase Mode
        Cmd->>Runner: rebaseMigration(onto, force, tag, config)
        Runner->>Gen: Identify local vs incoming migrations
        Gen->>Reg: Read conflict markers
        Reg-->>Gen: Local & incoming migration IDs
        alt Force Disabled & Unsafe Changes
            Runner-->>Cmd: Rollback / Error
            Cmd-->>User: Abort rebase
        else Force Enabled or Safe Changes
            Runner->>Gen: Generate unified migration (on top of onto)
            Gen-->>Runner: New migration created
            Runner->>Reg: Update registry (remove conflicts, add new migration)
            Reg-->>Runner: Registry updated
            Runner-->>Cmd: Rebase complete
            Cmd-->>User: Migration consolidated, old migrations deleted
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~35 minutes

Pre-merge checks

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: Add rebase migration command' clearly and concisely describes the main change—introduction of a new CLI command for rebasing migrations.
Description check ✅ Passed The PR description fully addresses the template: it explains the feature (rebase-migration command), lists the fixed issue (#4503), and the author has checked all pre-launch checklist items.
Linked Issues check ✅ Passed The PR implementation addresses all core coding requirements from #4503: parsing migration conflicts, identifying local migrations, generating unified migrations, backing up deleted migrations, and providing a CLI command to automate resolution.
Out of Scope Changes check ✅ Passed Changes are scoped to the rebase-migration feature: new command, runner class, comprehensive tests, test utilities, and supporting refactors in create-migration. All changes directly support the feature's objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart (1)

168-185: Consider grouping version-related tests.

The two version tests at lines 168 and 176 are closely related (both test version display functionality) and could be grouped together for better organization.

💡 Suggested grouping
+  group('Version display - ', () {
-  test('Given version subcommand when run then prints only version', () async {
+    test('Given version subcommand when run then prints only version', () async {
-    await fixture.runner.run(['version']);
+      await fixture.runner.run(['version']);

-    var logOutput = fixture.logOutput;
-    expect(logOutput.messages, hasLength(1));
-    expect(logOutput.messages.first, equals('Serverpod version: 1.1.0'));
-  });
+      var logOutput = fixture.logOutput;
+      expect(logOutput.messages, hasLength(1));
+      expect(logOutput.messages.first, equals('Serverpod version: 1.1.0'));
+    });

-  test(
-    'Given --version flag when run then should exit early and not show help',
-    () async {
-      await fixture.runner.run(['--version']);
+    test(
+      'Given --version flag when run then should exit early and not show help',
+      () async {
+        await fixture.runner.run(['--version']);

-      var logOutput = fixture.logOutput;
-      expect(logOutput.messages, hasLength(1));
-      expect(logOutput.messages.first, equals('Serverpod version: 1.1.0'));
-    },
-  );
+        var logOutput = fixture.logOutput;
+        expect(logOutput.messages, hasLength(1));
+        expect(logOutput.messages.first, equals('Serverpod version: 1.1.0'));
+      },
+    );
+  });

As per coding guidelines, related test cases should be grouped where appropriate.

tools/serverpod_cli/test/commands/rebase_migration_test.dart (1)

127-129: Missing cleanup for created test directories.

The createValidProject function creates a mock project directory but tearDown only resets the logger. This could leave orphaned test directories and cause isolation issues if tests run in parallel.

🔎 Proposed fix to add directory cleanup
+  late Directory? createdProjectDir;
+
   /// Creates a valid project for testing
   Future<void> createValidProject({bool withDatabase = true}) async {
     final currentDir = createMockServerpodProject(
       projectName: 'myapp',
       generatorYamlContent:
           '''
 type: server
 features:
   database: $withDatabase
 ''',
     );
     await currentDir.create();
     Directory.current = currentDir.io;
+    createdProjectDir = currentDir.io;
   }

   tearDown(() {
     resetLogger();
+    if (createdProjectDir?.existsSync() ?? false) {
+      createdProjectDir!.deleteSync(recursive: true);
+    }
+    createdProjectDir = null;
   });
tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart (3)

113-115: Missing tearDown for project cleanup.

The setUp creates a full project using serverpod create but there's no corresponding tearDown to clean up. This could lead to disk space issues and test pollution when running the suite repeatedly.

🔎 Proposed fix to add tearDown cleanup
   setUp(() async {
     await createProject();
   });

+  tearDown(() async {
+    final projectDir = Directory(path.join(d.sandbox, projectName));
+    if (projectDir.existsSync()) {
+      projectDir.deleteSync(recursive: true);
+    }
+  });

315-336: Redundant delays in test body.

The createMigration helper at line 60-61 already includes a 2ms delay for migration ordering. The additional Future.delayed calls here are redundant.

🔎 Proposed simplification
             // 2. Second migration (v2)
             await writeModel(
               'other',
               ['name: String'],
             );
             await createMigration();

-            // Pause to ensure v1 is created before v2
-            await Future.delayed(const Duration(milliseconds: 2));
-
             // 3. Third migration (v3)
             await writeModel(
               'third',
               ['name: String'],
             );
             await createMigration();

-            // Pause to ensure v2 is created before v3
-            await Future.delayed(const Duration(milliseconds: 2));
-
             // 4. Run rebase-migration --check --onto v1

495-497: Skipped test group reduces coverage.

This test group for registry conflict scenarios is marked skip: true. Per the PR comments, there are concerns about e2e test isolation due to database state not being reset between tests.

Consider either:

  1. Opening an issue to track enabling these tests
  2. Adding the isolation/cleanup needed for the tests to pass reliably

Do you want me to help open an issue to track this work?

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1aaca44 and 2a8f1fa.

⛔ Files ignored due to path filters (6)
  • tools/serverpod_cli/lib/src/migrations/generator.dart is excluded by !**/migrations/**
  • tools/serverpod_cli/lib/src/migrations/migration_registry.dart is excluded by !**/migrations/**
  • tools/serverpod_cli/lib/src/migrations/migration_registry_file.dart is excluded by !**/migrations/**
  • tools/serverpod_cli/lib/src/migrations/rebase_migration_runner.dart is excluded by !**/migrations/**
  • tools/serverpod_cli/test/migrations/migration_registry_file_test.dart is excluded by !**/migrations/**
  • tools/serverpod_cli/test/migrations/rebase_migration_runner_test.dart is excluded by !**/migrations/**
📒 Files selected for processing (12)
  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition.json
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition.sql
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition_project.json
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/migration.json
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/migration.sql
  • tools/serverpod_cli/bin/serverpod_cli.dart
  • tools/serverpod_cli/lib/src/commands/create_migration.dart
  • tools/serverpod_cli/lib/src/commands/rebase_migration.dart
  • tools/serverpod_cli/test/commands/rebase_migration_test.dart
  • tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
  • tools/serverpod_cli/test/test_util/mock_log.dart
🧰 Additional context used
📓 Path-based instructions (2)
**/*test.dart

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*test.dart: When using group() with test(), ensure each statement ('Given', 'When', 'Then') appears only once in the combined description to avoid duplication
Place passing/success test cases at the top of test files before error test cases for the same functionality
Group related test cases using group() where appropriate

Files:

  • tools/serverpod_cli/test/commands/rebase_migration_test.dart
  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
  • tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
**/*.dart

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.dart: Follow Dart formatting conventions with dart format command
Run 'dart format .' to format all code before committing
Run 'melos lint_strict' or 'util/run_tests_analyze' to check code quality before committing, ensuring compliance with CI strict mode

Files:

  • tools/serverpod_cli/test/commands/rebase_migration_test.dart
  • tools/serverpod_cli/lib/src/commands/create_migration.dart
  • tools/serverpod_cli/test/test_util/mock_log.dart
  • tools/serverpod_cli/lib/src/commands/rebase_migration.dart
  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
  • tools/serverpod_cli/bin/serverpod_cli.dart
  • tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
🧠 Learnings (15)
📚 Learning: 2025-08-25T19:46:58.073Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3917
File: modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/analysis_options.yaml:3-6
Timestamp: 2025-08-25T19:46:58.073Z
Learning: In Serverpod, test tool paths like `test/integration/test_tools/serverpod_test_tools.dart` are configured per project in the "generator.yaml" file and managed by a generator system, so they don't need to be updated manually across all files at once.

Applied to files:

  • tools/serverpod_cli/test/commands/rebase_migration_test.dart
  • tools/serverpod_cli/lib/src/commands/create_migration.dart
  • tools/serverpod_cli/test/test_util/mock_log.dart
  • tools/serverpod_cli/lib/src/commands/rebase_migration.dart
  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition.json
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition_project.json
  • tools/serverpod_cli/bin/serverpod_cli.dart
  • tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
📚 Learning: 2025-12-11T03:56:54.151Z
Learnt from: CR
Repo: serverpod/serverpod PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-11T03:56:54.151Z
Learning: Verify example projects still work before submitting PR by running example servers with 'dart bin/main.dart --apply-migrations'

Applied to files:

  • tools/serverpod_cli/test/commands/rebase_migration_test.dart
  • tools/serverpod_cli/lib/src/commands/create_migration.dart
  • tools/serverpod_cli/lib/src/commands/rebase_migration.dart
  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
  • tools/serverpod_cli/bin/serverpod_cli.dart
📚 Learning: 2025-07-02T16:09:27.702Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3747
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/pubspec.yaml:37-38
Timestamp: 2025-07-02T16:09:27.702Z
Learning: In Serverpod migration testing, it's appropriate for test servers like serverpod_new_auth_test_server to include dependencies on both legacy packages (e.g., serverpod_auth_server) and new modular packages to enable comprehensive testing of migration paths from old to new authentication systems.

Applied to files:

  • tools/serverpod_cli/test/commands/rebase_migration_test.dart
  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition_project.json
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition.sql
  • tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
📚 Learning: 2025-12-11T03:56:54.151Z
Learnt from: CR
Repo: serverpod/serverpod PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-11T03:56:54.151Z
Learning: Applies to **/*test.dart : Group related test cases using group() where appropriate

Applied to files:

  • tools/serverpod_cli/test/test_util/mock_log.dart
  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
  • tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
📚 Learning: 2025-12-11T03:56:54.151Z
Learnt from: CR
Repo: serverpod/serverpod PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-11T03:56:54.151Z
Learning: Applies to **/*.dart : Follow Dart formatting conventions with dart format command

Applied to files:

  • tools/serverpod_cli/lib/src/commands/rebase_migration.dart
  • tools/serverpod_cli/bin/serverpod_cli.dart
📚 Learning: 2025-12-11T03:56:54.151Z
Learnt from: CR
Repo: serverpod/serverpod PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-11T03:56:54.151Z
Learning: Applies to **/*test.dart : When using group() with test(), ensure each statement ('Given', 'When', 'Then') appears only once in the combined description to avoid duplication

Applied to files:

  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
📚 Learning: 2025-07-02T16:07:50.947Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

Applied to files:

  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition_project.json
  • tools/serverpod_cli/bin/serverpod_cli.dart
  • tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
📚 Learning: 2025-11-04T12:09:52.649Z
Learnt from: marcelomendoncasoares
Repo: serverpod/serverpod PR: 4150
File: examples/auth/auth_flutter/lib/widgets/profile_info.dart:23-30
Timestamp: 2025-11-04T12:09:52.649Z
Learning: In Serverpod example and testing projects (e.g., examples/auth/auth_flutter), prefer letting errors bubble up naturally rather than handling them gracefully with catchError or try-catch blocks. This helps developers see what went wrong during development and testing.

Applied to files:

  • tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart
  • tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
📚 Learning: 2025-06-17T11:34:13.289Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3666
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/README.md:3-8
Timestamp: 2025-06-17T11:34:13.289Z
Learning: The README.md files in the serverpod_auth_migration module directories are auto-generated and get overwritten by utility scripts, so manual updates should be avoided until proper documentation is added during feature rollout.

Applied to files:

  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition_project.json
📚 Learning: 2025-06-17T11:40:09.088Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3666
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_client/CHANGELOG.md:1-7
Timestamp: 2025-06-17T11:40:09.088Z
Learning: CHANGELOG.md files in the serverpod_auth_migration modules (client and server) are auto-generated and cannot be manually modified during the development process.

Applied to files:

  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition_project.json
📚 Learning: 2025-07-16T14:22:21.330Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3791
File: modules/new_serverpod_auth/serverpod_auth_apple_account/serverpod_auth_apple_account_server/lib/src/models/apple_account.spy.yaml:16-21
Timestamp: 2025-07-16T14:22:21.330Z
Learning: In Serverpod, tp prefers requiring explicit field setting without default values for new database schemas that haven't been deployed yet, rather than providing defaults, to ensure that critical metadata (like refreshTokenRequestedWithBundleIdentifier in Apple authentication) is consciously set by the application code. This approach is valid for new schemas since there are no existing rows to cause migration failures.

Applied to files:

  • tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition_project.json
📚 Learning: 2025-12-11T03:56:54.151Z
Learnt from: CR
Repo: serverpod/serverpod PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-11T03:56:54.151Z
Learning: Activate serverpod_cli from source using 'dart pub global activate --source path tools/serverpod_cli' after installation for development

Applied to files:

  • tools/serverpod_cli/bin/serverpod_cli.dart
📚 Learning: 2025-06-27T08:39:36.440Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3721
File: util/pub_get_all:0-0
Timestamp: 2025-06-27T08:39:36.440Z
Learning: In the Serverpod project, `dart pub get` commands work fine on Flutter packages both locally and in CI environments, even when the package has `flutter: sdk: flutter` dependencies in pubspec.yaml. The technical constraint of Flutter SDK dependencies causing `dart pub` failures may not apply in all environments or recent Dart versions.

Applied to files:

  • tools/serverpod_cli/bin/serverpod_cli.dart
📚 Learning: 2025-12-11T03:56:54.151Z
Learnt from: CR
Repo: serverpod/serverpod PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-11T03:56:54.151Z
Learning: Update pubspec files from templates using 'util/update_pubspecs' after template changes

Applied to files:

  • tools/serverpod_cli/bin/serverpod_cli.dart
📚 Learning: 2025-06-16T12:07:26.018Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3651
File: modules/new_serverpod_auth/serverpod_auth_email_account/serverpod_auth_email_account_server/lib/src/business/email_accounts.dart:35-39
Timestamp: 2025-06-16T12:07:26.018Z
Learning: The `withServerpod` test helper runs tests within a transaction, which may require adapting database queries to accept transaction parameters for proper snapshot consistency during testing.

Applied to files:

  • tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart
🔇 Additional comments (21)
tools/serverpod_cli/test/runner/serverpod_command_runner_test.dart (3)

10-10: LGTM: Good refactoring to shared test utilities.

Extracting mock implementations to a shared utility promotes code reuse and maintainability across test files.


12-91: LGTM: Well-structured test fixtures and mocks.

The mock command classes and TestFixture pattern provide clean, maintainable test infrastructure. The createTestFixture factory function ensures consistent test setup with proper dependency wiring.


93-107: LGTM: Proper test setup and teardown.

The setup structure correctly initializes the logger once for all tests while creating fresh fixtures per test, ensuring proper test isolation.

tools/serverpod_cli/lib/src/commands/create_migration.dart (3)

67-108: LGTM! Clean extraction of migration logic into a testable runner.

The refactoring successfully separates concerns by extracting migration creation logic into CreateMigrationRunner. This enables unit testing and reuse (as demonstrated by the rebase-migration command), while preserving existing behavior and error handling.


111-127: LGTM! Well-documented runner class.

The CreateMigrationRunner class is properly documented with template comments and clear field descriptions. The design follows good practices by making the runner configurable via constructor parameters.


148-220: LGTM! Enhanced method signature supports downstream usage.

The createMigration method now returns String? (the migration name on success, null when no changes detected) instead of void. This enhancement enables callers like RebaseMigrationRunner to access the generated migration name without re-querying the filesystem.

tools/serverpod_cli/lib/src/commands/rebase_migration.dart (4)

15-47: LGTM! Well-structured options with proper reuse.

The RebaseMigrationOption enum follows the established pattern and correctly reuses force and tag options from CreateMigrationCommand, avoiding duplication and ensuring consistency across commands.


52-66: LGTM! Testable design with dependency injection.

The nullable rebaseMigrationRunner field annotated with @visibleForTesting enables proper unit testing by allowing mock injection, while still providing production defaults. The command metadata is clear and descriptive.


83-86: LGTM! Proper validation prevents empty --onto values.

The validation correctly catches the edge case where --onto is specified but empty (e.g., --onto ""), providing a clear error message before proceeding with the migration.


117-142: LGTM! Consolidated environment validation.

Extracting validation into _validateCommandEnvironment promotes maintainability and follows DRY principles. The method properly validates both config loading and database feature enablement with informative error messages.

tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/migration.json (1)

1-53: LGTM! Valid test fixture for e2e migration testing.

This migration JSON correctly defines a DatabaseMigration that creates a "third" table with standard id/name columns and a primary key index. The format conforms to Serverpod's migration schema (migrationApiVersion 1) and complements the parallel test fixtures in the incoming_1 directory for comprehensive rebase-migration testing.

tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition_project.json (1)

1-150: LGTM! Valid test fixture representing post-migration database state.

This DatabaseDefinition correctly describes the complete database schema with three tables (example, other, third) and their installed module versions. The consistent table structure and proper index definitions align with the migration.json fixture, enabling accurate e2e testing of the rebase-migration workflow.

tools/serverpod_cli/bin/serverpod_cli.dart (2)

14-14: LGTM! Proper import addition.

The import for RebaseMigrationCommand is correctly placed in alphabetical order with other command imports.


83-83: LGTM! Command successfully wired into CLI.

The RebaseMigrationCommand() is properly registered in the command runner, making it available via serverpod rebase-migration. The placement between CreateRepairMigrationCommand and RunCommand is logical and follows the existing pattern.

tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/migration.sql (1)

1-45: LGTM!

This SQL migration test fixture is well-structured with proper transaction boundaries and follows Serverpod's migration patterns. The ON CONFLICT upsert strategy for migration versions is appropriate for idempotent migrations.

tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition.json (1)

1-2835: LGTM!

This JSON definition file is a comprehensive test fixture representing a complete Serverpod database schema. The structure correctly follows Serverpod's DatabaseDefinition format with proper table definitions, column types, indexes, foreign keys, and installed module versions.

tools/serverpod_cli/test/commands/rebase_migration_test.dart (1)

145-227: Well-structured test coverage for command validation.

The test suite properly covers:

  • Input validation (empty --onto)
  • Environment validation (missing config, disabled database feature)
  • Correct delegation between rebaseMigration and checkMigration based on the --check flag

The test descriptions follow the Given/When/Then pattern per coding guidelines.

tests/serverpod_cli_e2e_test/test/rebase_migration_test.dart (2)

625-627: Another skipped test group for destructive changes.

Similar to the registry conflict tests, this group is also skipped. Both groups appear to test important edge cases for the rebase-migration command.

These tests cover critical scenarios (rollback on destructive changes, --force flag behavior) that should be validated before the feature is considered complete.


117-179: Good test structure following coding guidelines.

The test groups follow the Given/When/Then pattern appropriately:

  • Group: "Given --onto specified"
  • Test: "when there are local migrations then migrations are collapsed into one"

The assertions verify both the migration directory state and registry contents, providing comprehensive validation.

tools/serverpod_cli/test/test_util/mock_log.dart (1)

1-86: LGTM!

Well-structured test utilities that properly extend/implement the cli_tools interfaces. The MockLogOutput aggregates messages by category, MockLogger routes log calls to the output, and MockAnalytics tracks events. The reset() method returning this enables fluent chaining if needed.

tests/serverpod_cli_e2e_test/test/test_migrations/incoming_1/definition.sql (1)

1-649: LGTM!

This SQL definition file is a comprehensive test fixture providing:

  • A properly attributed gen_random_uuid_v7() function (MIT licensed)
  • Complete table schemas for Serverpod core and authentication modules
  • Foreign key relationships with appropriate cascade behaviors
  • Migration version tracking with upsert semantics

The schema correctly mirrors the JSON definition and follows PostgreSQL best practices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Append migration command

1 participant