|
1 | | -Stormberry comes with a database migration tool, to create or update the schema of your database. |
| 1 | +Stormberry comes with a database migration system, to create or update the schema of your database. |
2 | 2 |
|
3 | | -To use this run the following command from the root folder of your project. |
| 3 | +You can either call the migration tool from your terminal, or use the programmatic migration API. |
| 4 | + |
| 5 | +## Migration CLI |
| 6 | + |
| 7 | +To use the migration CLI run the following command from the root folder of your project: |
4 | 8 |
|
5 | 9 | ``` |
6 | 10 | dart run stormberry migrate |
@@ -38,4 +42,47 @@ The tool supported the following options: |
38 | 42 |
|
39 | 43 | --- |
40 | 44 |
|
41 | | -*🎉 Congrats, you followed the tour until the end. Now you know everything about this package.* |
| 45 | +## Migration API |
| 46 | + |
| 47 | +To migrate your database from your own code, first enable the `database_schema` builder like this: |
| 48 | + |
| 49 | +```yaml |
| 50 | +// build.yaml |
| 51 | +targets: |
| 52 | + $default: |
| 53 | + builders: |
| 54 | + stormberry|database_schema: |
| 55 | + enabled: true |
| 56 | +``` |
| 57 | +
|
| 58 | +This will generate a `lib/database.schema.dart` file next time you run code generation, containing a global `DatabaseSchema schema` variable of your current schema. |
| 59 | + |
| 60 | +To migrate your database to this schema, do the following: |
| 61 | + |
| 62 | +```dart |
| 63 | +// Import the 'migrate.dart' library. |
| 64 | +import 'package:stormberry/migrate.dart'; |
| 65 | +
|
| 66 | +Future<void> migrate() async { |
| 67 | + // 1. Connect to your database |
| 68 | + final Database db = ... |
| 69 | +
|
| 70 | + // 2. Compute the schema diff between your live database schema and the generated target `schema`. |
| 71 | + final diff = await schema.computeDiff(db); |
| 72 | + |
| 73 | + // 3. (Optional) Print the schema diff to stdout. |
| 74 | + diff.printToConsole(); |
| 75 | + |
| 76 | + try { |
| 77 | + // Always use a transaction to not break your database!! |
| 78 | + await db.runTx((session) async { |
| 79 | + |
| 80 | + // 4. Apply the necessary patches to migrate to the target schema. |
| 81 | + await diff.patch(session); |
| 82 | + }); |
| 83 | + print('Migration succeeded'); |
| 84 | + } catch (e) { |
| 85 | + print('Migration failed. All changes reverted.'); |
| 86 | + } |
| 87 | +} |
| 88 | +``` |
0 commit comments