|
| 1 | +import 'package:logging/logging.dart'; |
| 2 | +import 'package:mongo_dart/mongo_dart.dart'; |
| 3 | + |
| 4 | +/// {@template migration} |
| 5 | +/// An abstract base class for defining database migration scripts. |
| 6 | +/// |
| 7 | +/// Each concrete migration must extend this class and implement the [up] and |
| 8 | +/// [down] methods. Migrations are identified by a unique [version] string |
| 9 | +/// (following the `YYYYMMDDHHMMSS` format) and a [description]. |
| 10 | +/// |
| 11 | +/// Implementations of [up] and [down] must be **idempotent**, meaning they |
| 12 | +/// can be safely run multiple times without causing errors or incorrect data. |
| 13 | +/// This is crucial for robust database schema evolution. |
| 14 | +/// {@endtemplate} |
| 15 | +abstract class Migration { |
| 16 | + /// {@macro migration} |
| 17 | + const Migration({ |
| 18 | + required this.version, |
| 19 | + required this.description, |
| 20 | + this.gitHubPullRequest, |
| 21 | + }); |
| 22 | + |
| 23 | + /// A unique identifier for the migration, following the `YYYYMMDDHHMMSS` |
| 24 | + /// format (e.g., '20250924083500'). This ensures chronological ordering. |
| 25 | + final String version; |
| 26 | + |
| 27 | + /// A human-readable description of the migration's purpose. |
| 28 | + final String description; |
| 29 | + |
| 30 | + /// An optional URL or identifier for the GitHub Pull Request that introduced |
| 31 | + /// the schema changes addressed by this migration. |
| 32 | + /// |
| 33 | + /// This provides valuable context for future maintainers, linking the |
| 34 | + /// database migration directly to the code changes that necessitated it. |
| 35 | + final String? gitHubPullRequest; |
| 36 | + |
| 37 | + /// Applies the migration, performing necessary schema changes or data |
| 38 | + /// transformations. |
| 39 | + /// |
| 40 | + /// This method is executed when the migration is run. It receives the |
| 41 | + /// MongoDB [db] instance and a [Logger] for logging progress and errors. |
| 42 | + /// |
| 43 | + /// Implementations **must** be idempotent. |
| 44 | + Future<void> up(Db db, Logger log); |
| 45 | + |
| 46 | + /// Reverts the migration, undoing the changes made by the [up] method. |
| 47 | + /// |
| 48 | + /// This method is executed when a migration needs to be rolled back. It |
| 49 | + /// receives the MongoDB [db] instance and a [Logger]. |
| 50 | + /// |
| 51 | + /// Implementations **must** be idempotent. While optional for simple |
| 52 | + /// forward-only migrations, providing a `down` method is a best practice |
| 53 | + /// for professional systems to enable rollback capabilities. |
| 54 | + Future<void> down(Db db, Logger log); |
| 55 | +} |
0 commit comments