Migrations

DianaDb has its own migrations storage out of the box. You register a migration with the addMigration ODM method:
dianaDb.addMigration({
  index: 1, // unique integer index
  name: 'MyFirstMigration', // unique name
  up: async () => {
    // do something
  },
  down: async () => {
    // roll back what up() did
  },
});
  

A migration can affect many databases and collections. There is only one list of applied migrations, so names and indexes must be unique — addMigration throws on a duplicate index or name. Never change the code of a migration after it has run.

Running migrations

await dianaDb.connect(5000);

const applied = await dianaDb.migrateUp('test');
// [{ name: 'MyFirstMigration', status: 'up' }]

const reverted = await dianaDb.migrateDown('test', 1); // revert only the last applied migration
// [{ name: 'MyFirstMigration', status: 'down' }]

const recorded = await dianaDb.getMigrations('test'); // names recorded as applied on the server
  
  • The server keeps one global list of applied migrations but checks write access on a database, so every call needs one: pass it, or set the database constructor option (or the connection string path) and call migrateUp() without arguments. Without either, the ODM throws a migration error before sending anything.
  • migrateUp runs pending migrations in ascending index order.
  • migrateDown reverts applied migrations in descending index order — all of them, or only the last steps.
  • Both resolve with the server's record of each migration they ran, MigrationInfo: { name: string; status: 'up' | 'down' }. The server answers every call with { migration: { name, status } }, and the ODM checks that the name and status match.
  • If the server doesn't confirm a migration, the call throws a migration error naming it. Its up() / down() has already run at that point, so check its effects before retrying.