-
Notifications
You must be signed in to change notification settings - Fork 0
Feat/generic db migration system #62
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
Show all changes
15 commits
Select commit
Hold shift + click to select a range
3dcf1d0
feat(database): add migration base class for database schema evolution
fulleni a95ffca
feat(database): add migration to refactor adConfig to role-based stru…
fulleni f447df9
feat(database): create central list for all database migrations
fulleni 2651006
feat(database): implement database migration service
fulleni d3c1a59
feat(database): add database migration service and update seeding pro…
fulleni 4a27fe2
refactor(database): improve RemoteConfig seeding and logging
fulleni 6002c18
docs(README): add section on automated database migrations
fulleni 860f8c1
refactor(database): enhance Migration class with PR metadata
fulleni 1eec653
refactor(database): update migration class and log message
fulleni a4ec1ec
docs(database): update migration documentation
fulleni 1563cd6
refactor(database): enhance database migration system
fulleni 26ea858
docs(README): update database migration descriptions
fulleni 1fb7ad1
style: format
fulleni 0dfe286
refactor(migration): update documentation and remove ignored lint
fulleni 249841f
fix(database): sort migrations before applying
fulleni 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import 'package:logging/logging.dart'; | ||
import 'package:mongo_dart/mongo_dart.dart'; | ||
|
||
/// {@template migration} | ||
/// An abstract base class for defining database migration scripts. | ||
/// | ||
/// Each concrete migration must extend this class and implement the [up] and | ||
/// [down] methods. Migrations are identified by a unique [prDate] string | ||
/// (following the `YYYYMMDDHHMMSS` format) and a [prSummary]. | ||
/// | ||
/// Implementations of [up] and [down] must be **idempotent**, meaning they | ||
/// can be safely run multiple times without causing errors or incorrect data. | ||
/// This is crucial for robust database schema evolution. | ||
/// {@endtemplate} | ||
abstract class Migration { | ||
/// {@macro migration} | ||
const Migration({ | ||
required this.prDate, | ||
required this.prSummary, | ||
required this.prId, | ||
}); | ||
|
||
/// The merge date and time of the Pull Request that introduced this | ||
/// migration, in `YYYYMMDDHHMMSS` format (e.g., '20250924083500'). | ||
/// | ||
/// This serves as the unique, chronological identifier for the migration, | ||
/// ensuring that migrations are applied in the correct order. | ||
final String prDate; | ||
|
||
/// A concise summary of the changes introduced by the Pull Request that | ||
/// this migration addresses. | ||
/// | ||
/// This provides a human-readable description of the migration's purpose. | ||
final String prSummary; | ||
|
||
/// The unique identifier of the GitHub Pull Request that introduced the | ||
/// schema changes addressed by this migration (e.g., '50'). | ||
/// | ||
/// This provides direct traceability, linking the database migration to the | ||
/// specific code changes on GitHub. | ||
final String prId; | ||
|
||
/// Applies the migration, performing necessary schema changes or data | ||
/// transformations. | ||
/// | ||
/// This method is executed when the migration is run. It receives the | ||
/// MongoDB [db] instance and a [Logger] for logging progress and errors. | ||
/// | ||
/// Implementations **must** be idempotent. | ||
Future<void> up(Db db, Logger log); | ||
|
||
/// Reverts the migration, undoing the changes made by the [up] method. | ||
/// | ||
/// This method is executed when a migration needs to be rolled back. It | ||
/// receives the MongoDB [db] instance and a [Logger]. | ||
/// | ||
/// Implementations **must** be idempotent. While optional for simple | ||
/// forward-only migrations, providing a `down` method is a best practice | ||
/// for professional systems to enable rollback capabilities. | ||
Future<void> down(Db db, Logger log); | ||
} |
160 changes: 160 additions & 0 deletions
160
lib/src/database/migrations/20250924084800__refactor_ad_config_to_role_based.dart
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,160 @@ | ||
// ignore_for_file: comment_references | ||
|
||
import 'package:core/core.dart'; | ||
import 'package:flutter_news_app_api_server_full_source_code/src/database/migration.dart'; | ||
import 'package:logging/logging.dart'; | ||
import 'package:mongo_dart/mongo_dart.dart'; | ||
|
||
/// {@template refactor_ad_config_to_role_based} | ||
/// A comprehensive migration to refactor the `adConfig` structure within | ||
/// `RemoteConfig` documents to a new role-based `visibleTo` map approach. | ||
/// | ||
/// This migration addresses significant changes introduced by a PR (see | ||
/// [gitHubPullRequest]) that aimed to enhance flexibility and maintainability | ||
/// of ad configurations. It transforms old, role-specific ad frequency and | ||
/// placement fields into new `visibleTo` maps for `FeedAdConfiguration`, | ||
/// `ArticleAdConfiguration`, and `InterstitialAdConfiguration`. | ||
/// | ||
/// The migration ensures that existing `RemoteConfig` documents are updated | ||
/// to conform to the latest model structure, preventing deserialization errors | ||
/// and enabling granular control over ad display for different user roles. | ||
/// {@endtemplate} | ||
class RefactorAdConfigToRoleBased extends Migration { | ||
/// {@macro refactor_ad_config_to_role_based} | ||
RefactorAdConfigToRoleBased() | ||
: super( | ||
prDate: '20250924084800', | ||
prSummary: 'Refactor adConfig to use role-based visibleTo maps', | ||
prId: '50', | ||
); | ||
|
||
@override | ||
Future<void> up(Db db, Logger log) async { | ||
log.info( | ||
'Applying migration PR#$prId (Date: $prDate): $prSummary.', | ||
); | ||
|
||
final remoteConfigCollection = db.collection('remote_configs'); | ||
|
||
// Define default FeedAdFrequencyConfig for roles | ||
const defaultGuestFeedAdFrequency = FeedAdFrequencyConfig( | ||
adFrequency: 5, | ||
adPlacementInterval: 3, | ||
); | ||
const defaultStandardUserFeedAdFrequency = FeedAdFrequencyConfig( | ||
adFrequency: 10, | ||
adPlacementInterval: 5, | ||
); | ||
// Define default InterstitialAdFrequencyConfig for roles | ||
const defaultGuestInterstitialAdFrequency = InterstitialAdFrequencyConfig( | ||
transitionsBeforeShowingInterstitialAds: 5, | ||
); | ||
const defaultStandardUserInterstitialAdFrequency = | ||
InterstitialAdFrequencyConfig( | ||
transitionsBeforeShowingInterstitialAds: 10, | ||
); | ||
|
||
// Define default ArticleAdSlot visibility for roles | ||
final defaultArticleAdSlots = { | ||
InArticleAdSlotType.aboveArticleContinueReadingButton.name: true, | ||
InArticleAdSlotType.belowArticleContinueReadingButton.name: true, | ||
}; | ||
|
||
final result = await remoteConfigCollection.updateMany( | ||
// Find documents that still have the old structure (e.g., old frequency fields) | ||
where.exists( | ||
'adConfig.feedAdConfiguration.frequencyConfig.guestAdFrequency', | ||
), | ||
ModifierBuilder() | ||
// --- FeedAdConfiguration Transformation --- | ||
// Remove old frequencyConfig fields | ||
..unset('adConfig.feedAdConfiguration.frequencyConfig.guestAdFrequency') | ||
..unset( | ||
'adConfig.feedAdConfiguration.frequencyConfig.guestAdPlacementInterval', | ||
) | ||
..unset( | ||
'adConfig.feedAdConfiguration.frequencyConfig.authenticatedAdFrequency', | ||
) | ||
..unset( | ||
'adConfig.feedAdConfiguration.frequencyConfig.authenticatedAdPlacementInterval', | ||
) | ||
..unset( | ||
'adConfig.feedAdConfiguration.frequencyConfig.premiumAdFrequency', | ||
) | ||
..unset( | ||
'adConfig.feedAdConfiguration.frequencyConfig.premiumAdPlacementInterval', | ||
) | ||
// Set the new visibleTo map for FeedAdConfiguration | ||
..set( | ||
'adConfig.feedAdConfiguration.visibleTo', | ||
{ | ||
AppUserRole.guestUser.name: defaultGuestFeedAdFrequency.toJson(), | ||
AppUserRole.standardUser.name: defaultStandardUserFeedAdFrequency | ||
.toJson(), | ||
}, | ||
) | ||
// --- ArticleAdConfiguration Transformation --- | ||
// Remove old inArticleAdSlotConfigurations list | ||
..unset('adConfig.articleAdConfiguration.inArticleAdSlotConfigurations') | ||
// Set the new visibleTo map for ArticleAdConfiguration | ||
..set( | ||
'adConfig.articleAdConfiguration.visibleTo', | ||
{ | ||
AppUserRole.guestUser.name: defaultArticleAdSlots, | ||
AppUserRole.standardUser.name: defaultArticleAdSlots, | ||
}, | ||
) | ||
// --- InterstitialAdConfiguration Transformation --- | ||
// Remove old feedInterstitialAdFrequencyConfig fields | ||
..unset( | ||
'adConfig.interstitialAdConfiguration.feedInterstitialAdFrequencyConfig.guestTransitionsBeforeShowingInterstitialAds', | ||
) | ||
..unset( | ||
'adConfig.interstitialAdConfiguration.feedInterstitialAdFrequencyConfig.standardUserTransitionsBeforeShowingInterstitialAds', | ||
) | ||
..unset( | ||
'adConfig.interstitialAdConfiguration.feedInterstitialAdFrequencyConfig.premiumUserTransitionsBeforeShowingInterstitialAds', | ||
) | ||
// Set the new visibleTo map for InterstitialAdConfiguration | ||
..set( | ||
'adConfig.interstitialAdConfiguration.visibleTo', | ||
{ | ||
AppUserRole.guestUser.name: defaultGuestInterstitialAdFrequency | ||
.toJson(), | ||
AppUserRole.standardUser.name: | ||
defaultStandardUserInterstitialAdFrequency.toJson(), | ||
}, | ||
), | ||
); | ||
|
||
log.info( | ||
'Updated ${result.nModified} remote_config documents ' | ||
'to new role-based adConfig structure.', | ||
); | ||
} | ||
|
||
@override | ||
Future<void> down(Db db, Logger log) async { | ||
log.warning( | ||
'Reverting migration: Revert adConfig to old structure ' | ||
'(not recommended for production).', | ||
); | ||
// This down migration is complex and primarily for development/testing rollback. | ||
// Reverting to the old structure would require re-introducing the old fields | ||
// and potentially losing data if the new structure was used. | ||
// For simplicity in this example, we'll just unset the new fields. | ||
final result = await db | ||
.collection('remote_configs') | ||
.updateMany( | ||
where.exists('adConfig.feedAdConfiguration.visibleTo'), | ||
ModifierBuilder() | ||
..unset('adConfig.feedAdConfiguration.visibleTo') | ||
..unset('adConfig.articleAdConfiguration.visibleTo') | ||
..unset('adConfig.interstitialAdConfiguration.visibleTo'), | ||
); | ||
log.warning( | ||
'Reverted ${result.nModified} remote_config documents ' | ||
'by unsetting new adConfig fields.', | ||
); | ||
} | ||
} |
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,13 @@ | ||
import 'package:flutter_news_app_api_server_full_source_code/src/database/migration.dart'; | ||
import 'package:flutter_news_app_api_server_full_source_code/src/database/migrations/20250924084800__refactor_ad_config_to_role_based.dart'; | ||
import 'package:flutter_news_app_api_server_full_source_code/src/services/database_migration_service.dart' | ||
show DatabaseMigrationService; | ||
|
||
/// A central list of all database migrations to be applied. | ||
/// | ||
/// New migration classes should be added to this list. The | ||
/// [DatabaseMigrationService] will automatically sort and apply them based on | ||
/// their `prDate` property. | ||
final List<Migration> allMigrations = [ | ||
RefactorAdConfigToRoleBased(), | ||
]; |
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.
Uh oh!
There was an error while loading. Please reload this page.